編輯:關於 Android 程式設計
Android 原生提供的 SwitchPreference 與 CheckBoxPreference,預設會把開關本身的點擊事件和整個 Preference 區域的點擊事件綁在一起。也就是說,不論你點的是標題文字還是右側的 Toggle 按鈕,效果完全相同。
但實務上經常需要把兩者拆開:點擊整齊的 Preference 區域時彈出對話框或跳轉到另一個 Activity,而點擊 Switch 時只切換開關狀態,不觸發任何跳轉。這篇文章整理了三種可行的實作方向。由於 SwitchPreference 與 CheckBoxPreference 都繼承自 TwoStatePreference,下面只以 SwitchPreference 為例說明,替換成 CheckBoxPreference 的做法完全一致。
最直覺的思路是自訂一個子類,覆寫 onClick 把事件攔下來。需要注意的是,在 Android 5.0(Lollipop)上還必須額外覆寫 onCreateView,主動把 Switch 的 clickable 設為 true,否則 Switch 根本收不到點擊事件——這個坑當初從 4.4 移植到 5.0 時讓我查了很久。
public class SmartSwitchPreference extends SwitchPreference {
public SmartSwitchPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public SmartSwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SmartSwitchPreference(Context context) {
super(context);
}
@Override
protected void onClick() {
// 這裡接手原本屬於整個 Preference 區域的點擊
}
// Android 5.0 以上必須保留這段,否則 Switch 拿不到點擊事件
@Override
protected View onCreateView(ViewGroup parent) {
View view = super.onCreateView(parent);
Switch v = (Switch) view.findViewById(com.android.internal.R.id.switchWidget);
if (v != null) {
v.setClickable(true);
}
return view;
}
}
限制:在 Android 5.0 上這個寫法只適用於有完整原始碼的 AOSP 編譯環境,因為 com.android.internal.R.id.switchWidget 屬於 framework 私有資源,一般 App 專案抓不到這個 ID。
比較通用也比較推薦的做法,是透過 setWidgetLayoutResource 把 Preference 右側的 widget 區域換成自訂配置,然後分別為「整個 Preference」和「Switch」掛上各自的監聽器。
<switch xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/prefrence_switch_id"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
這裡的 Switch 也可以換成 CheckBox 或 RadioButton,做法一樣。
public class GestureSwitchPreference extends SwitchPreference {
private Switch mSwitch;
private boolean mChecked = false;
private Context mContext;
public GestureSwitchPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
}
public GestureSwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
// 更新 widgetLayout,也就是把右側控制項換成我們自己的配置
setWidgetLayoutResource(R.layout.smart_gesture_switch);
}
public GestureSwitchPreference(Context context) {
super(context);
mContext = context;
setWidgetLayoutResource(R.layout.smart_gesture_switch);
}
@Override
protected void onBindView(View view) {
mSwitch = (Switch) view.findViewById(R.id.prefrence_switch_id);
// view 代表整個 Preference 區域,掛監聽器即可攔下區域點擊
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showToast("點到的是整個區域");
}
});
// Switch 自己的點擊事件
if (mSwitch != null) {
mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton button, boolean checked) {
mChecked = checked;
showToast("點到的是 Switch 本身");
}
});
}
setChecked(mChecked);
super.onBindView(view);
}
public boolean isChecked() {
return mChecked;
}
public void setChecked(boolean bChecked) {
mChecked = bChecked;
if (mSwitch != null) {
mSwitch.setChecked(bChecked);
}
}
private void showToast(String info) {
Toast.makeText(mContext, info, Toast.LENGTH_SHORT).show();
}
}
實務上更進一步的做法,是在這個類裡定義一組自訂監聽器介面(例如 onRegionClick 與 onSwitchClick),交由使用它的 Activity 去實作,讓視圖層與業務邏輯徹底分離。
<PreferenceScreen xmlns:android="https://schemas.android.com/apk/res/android">
<com.wtk.gesture.modules.GestureSwitchPreference
android:key="GestureSwitchPreference"
android:summary="概要"
android:title="標題" />
</PreferenceScreen>
public class SmartQuickGestureSettings extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.smart_quick_gesture_settings);
}
}
點擊 Preference 的整片區域:

單獨點擊 Switch:

這個方案的缺點:一是程式碼量偏大;二是需要自己維護開關狀態,否則離開頁面再回來時,Switch 會顯示成初始值而非使用者最後的選擇。
如果需求不止於一個開關,而是想在 Preference 裡放進 RadioGroup、圖片、說明文字等更複雜的內容,那就直接繼承 Preference 並用 setLayoutResource 換掉整個配置。
public class SmartGesturePrefrence extends Preference {
public static boolean isScreenOffBtn = true;
private Context mContext;
private OnRadioButtonCheckedListener mOnRadioButtonCheckedListener;
public interface OnRadioButtonCheckedListener {
void OnRadioButtonChecked(boolean isScreenOffView);
}
public void setOnRadioButtonCheckedListener(OnRadioButtonCheckedListener listener) {
mOnRadioButtonCheckedListener = listener;
}
public SmartGesturePrefrence(Context context) {
this(context, null);
}
public SmartGesturePrefrence(Context context, AttributeSet attrs) {
this(context, attrs, 0);
mContext = context;
}
public SmartGesturePrefrence(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
setLayoutResource(R.layout.gesture_preference_layout);
}
@Override
protected void onBindView(final View view) {
super.onBindView(view);
RadioGroup mRadioGroup = (RadioGroup) view.findViewById(R.id.radiogroup_gesture);
RadioButton mScreenOffButton = (RadioButton) view.findViewById(R.id.btn_screen_off);
RadioButton mPhoneCallingButton = (RadioButton) view.findViewById(R.id.btn_phone_calling);
mScreenOffButton.setChecked(isScreenOffBtn);
mPhoneCallingButton.setChecked(!isScreenOffBtn);
mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.btn_screen_off:
isScreenOffBtn = true;
if (mOnRadioButtonCheckedListener != null) {
mOnRadioButtonCheckedListener.OnRadioButtonChecked(true);
}
break;
case R.id.btn_phone_calling:
isScreenOffBtn = false;
if (mOnRadioButtonCheckedListener != null) {
mOnRadioButtonCheckedListener.OnRadioButtonChecked(false);
}
break;
}
}
});
}
}
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="20dp"
android:orientation="vertical"
android:paddingEnd="?android:attr/scrollbarSize"
android:paddingStart="?android:attr/scrollbarSize">
<RadioGroup
android:id="@+id/radiogroup_gesture"
android:layout_width="wrap_content"
android:layout_height="52dip"
android:layout_marginTop="6dip"
android:background="@android:color/black"
android:gravity="center_vertical"
android:orientation="horizontal">
<RadioButton
android:id="@+id/btn_screen_off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/zzz_radio_selector"
android:button="@null"
android:gravity="center"
android:text="@string/title_mode_idle"
android:textSize="16sp" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="@null"
android:scaleType="centerCrop"
android:src="@drawable/zzz_gesture_tab_space" />
<RadioButton
android:id="@+id/btn_phone_calling"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/zzz_radio_selector"
android:button="@null"
android:gravity="center"
android:text="@string/title_mode_call"
android:textSize="16sp" />
</RadioGroup>
<TextView
android:id="@+id/hint_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dip"
android:layout_marginRight="6dip"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:singleLine="true"
android:text="@string/gesture_operate_description"
android:textAppearance="?android:attr/textAppearanceSmall"
android:visibility="gone" />
</LinearLayout>


只是想把開關和區域點擊拆開,方案二最平衡;專案有完整 AOSP 原始碼、追求最小改動,方案一可行;需要高度自訂的視覺呈現,方案三最自由。三者共通的關鍵觀念其實只有一個:把「容器」與「控制項」的觸摸事件明確分派,不要讓系統預設的綁定替你決定行為。
Android 常用選擇器組件 CalendarView、DatePicker、TimePicker 與 NumberPicker 使用大全
本文一起複習幾個常用的基礎 UI 組件。Android 對這些組件封裝得非常完善,基本上套上屬性就能直接用,極大減輕了開發者的負擔;當然如果想深入研究,這其中仍有不少值得
深入解析 Android 官方 MVP 架構示例項目
本文就來具體看看官方示例究竟是如何實現 MVP 的。先從總體輪廓說起,業務代碼這裡僅列出任務詳情頁(taskDetail)的相關類,其他業務模組的組織方式類似。 基
仿微信底部 Tab 切換實作:拋棄 TitlePagerTabStrip 的輕量 ViewPager 方案
網路上的 Tab 教學品質參差,最常見的寫法是 TitlePagerTabStrip 搭配 ViewPager。但實測下來,TitlePagerTabStrip 有個挺惱
Android 手機衛士實戰:綁定 SIM 卡序列號與防盜攔截
接著處理導航流程中的第二個引導頁——SIM 卡綁定。 這個功能的思路是:把當前 SIM 卡的序列號存進 SharedPreferences,日後一旦換卡,就能對比出異常