Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 組件化開發(2):用 GridView 實作網格布局的 RadioButton 矩陣

編輯:關於 Android 程式設計

前言

一般我們用 RadioGroup 包住一批 RadioButton,就能拿到「單選互斥」的效果,省心省力。問題是 RadioGroup 骨子裡只是一個耿直的 LinearLayout,只能直排或橫排。當需求變成「N 列 × M 欄的單選矩陣」時,它就完全使不上力了。

下面分享一種可行的思路:把單選邏輯從容器搬到 Adapter 裡自己實作。先看效果圖:

思路

提到網格布局,最直接的就是系統的 GridView。我們把自訂的單選項放進 GridView,互斥判斷由 Adapter 負責——因為只有 Adapter 同時掌握「全部項目」與「目前選中項」這兩份資訊。

1. 自訂 RadioButton:IconRadioButton

/**
 * 自訂的單選項:本質是一個 LinearLayout,
 * 內部封裝了「依選中狀態切換圖示與文字樣式」的能力。
 */
public class IconRadioButton extends LinearLayout {

    private Context mContext;
    private Resources mResources;
    private boolean mIsCheck;
    private View mContentView;
    private ImageView mRadio;
    private TextView mTextView;
    private ColorStateList mTextColor;

    public IconRadioButton(Context context) {
        this(context, null);
    }

    public IconRadioButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public IconRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mContext = context;
        mResources = context.getResources();
        mContentView = LayoutInflater.from(context).inflate(R.layout.btn_icon_radio, this);
        mRadio = (ImageView) mContentView.findViewById(R.id.radio);
        mTextView = (TextView) mContentView.findViewById(R.id.text);
    }

    public void setChecked(boolean isChecked) {
        mIsCheck = isChecked;
        changeUIByChecked(isChecked);
    }

    public boolean isChecked() {
        return mIsCheck;
    }

    private void changeUIByChecked(boolean isChecked) {
        if (mRadio.getVisibility() != GONE) {
            mRadio.setImageResource(isChecked
                    ? R.drawable.radio_selected
                    : R.drawable.radio_unselected);
        }
        mTextView.setEnabled(isChecked);
    }

    public void setTextColor(ColorStateList color) {
        mTextColor = color;
        mTextView.setTextColor(color);
    }

    public void setText(CharSequence text) {
        mTextView.setText(text);
    }

    public void setText(int resId) {
        mTextView.setText(resId);
    }

    /** true 表示隱藏圓點,適合當作 Tab 切換按鈕使用 */
    public void hiddenRadio(boolean isHidden) {
        mRadio.setVisibility(isHidden ? GONE : VISIBLE);
    }
}

配套的 btn_icon_radio.xml 也很單純,就是一個橫向 LinearLayout 裡擺 ImageView 與 TextView:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="left"
    android:orientation="horizontal"
    android:paddingBottom="5dp"
    android:paddingTop="5dp">

    <ImageView
        android:id="@+id/radio"
        android:layout_width="42dp"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:src="@drawable/radio_selected" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:gravity="center"
        android:textColor="#FF999999"
        android:textSize="14dp" />
</LinearLayout>

2. 定義資料模型 RadioItemModel

把「文字、是否選中、是否隱藏圓點、文字顏色」四項屬性收進一個模型,Adapter 與 View 之間就有了清楚的契約。

public class RadioItemModel {

    public String text;              // 顯示文字
    public boolean isChecked;        // 是否選中
    public boolean hiddenRadio;      // 是否隱藏圓點
    public ColorStateList textColor; // 不同狀態下的文字顏色

    public RadioItemModel(String text, boolean isChecked,
                          boolean hiddenRadio, ColorStateList textColor) {
        this.text = text;
        this.isChecked = isChecked;
        this.hiddenRadio = hiddenRadio;
        this.textColor = textColor;
    }

    public RadioItemModel(String text) {
        this(text, false, false, null);
    }

    public void setText(String text) { this.text = text; }
    public String getText() { return text; }
    public boolean isChecked() { return isChecked; }
}

其中 ColorStateList 是關鍵角色,它能讓文字依 state_pressed、state_enabled 等狀態自動換色,不必在程式碼裡到處寫 if。

3. 定義 Adapter:互斥邏輯的根據地

/**
 * 單選矩陣的 Adapter。
 * 系統的 RadioGroup 只能線性排列,無法完成 N 行 N 列的網格布局,
 * 因此把互斥判斷搬到這裡自行實作。
 */
public class GridRadioAdapter extends BaseAdapter {

    private List<RadioItemModel> mList;
    private Context mContext;
    private Resources mResources;
    private OnItemCheckedListener mListener;

    public interface OnItemCheckedListener {
        void onItemChecked(RadioItemModel model, int position);
    }

    public void setOnItemCheckedListener(OnItemCheckedListener listener) {
        this.mListener = listener;
    }

    public GridRadioAdapter(Context context, List<RadioItemModel> list) {
        mContext = context;
        mList = list;
        check();
    }

    private void check() {
        if (mList != null && mList.size() > 0) {
            checkDefaultChecked();
            checkMutex();
        }
    }

    /** 預設選中:若外部沒有指定,就讓第一個項目被選中 */
    private void checkDefaultChecked() {
        for (RadioItemModel item : mList) {
            if (item.isChecked) return;
        }
        mList.get(0).isChecked = true;
    }

    /** 互斥檢查:若有多個項目被選中,只保留最後一個 */
    private void checkMutex() {
        int checkCount = 0;
        for (RadioItemModel item : mList) {
            if (item.isChecked) checkCount++;
        }
        if (checkCount >= 2) {
            setOtherUnChecked(checkCount - 1);
        }
    }

    private void setOtherUnChecked(int position) {
        for (int i = 0; i < mList.size(); i++) {
            mList.get(i).isChecked = (i == position);
        }
    }

    public RadioItemModel getItemChecked() {
        for (RadioItemModel item : mList) {
            if (item.isChecked) return item;
        }
        return null;
    }

    @Override
    public int getCount() {
        return mList == null ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return (mList != null && mList.size() > position) ? mList.get(position) : null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        IconRadioButton item = new IconRadioButton(mContext);
        final RadioItemModel model = mList.get(position);

        if (!TextUtils.isEmpty(model.text)) {
            item.setText(model.text);
        }
        item.setChecked(model.isChecked);
        if (model.textColor != null) {
            item.setTextColor(model.textColor);
        }
        item.hiddenRadio(model.hiddenRadio);

        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 已選中的項目不重複觸發
                if (!item.isChecked()) {
                    setOtherUnChecked(position);
                    if (mListener != null) {
                        mListener.onItemChecked(model, position);
                    }
                    notifyDataSetChanged();
                }
            }
        });
        return item;
    }

    public void addAll(List<RadioItemModel> list) {
        mList.clear();
        if (list != null && list.size() > 0) {
            mList.addAll(list);
            check();
            notifyDataSetChanged();
        }
    }
}

三個設計要點值得留意:

  1. checkDefaultChecked() 保證永遠有一個預設選中項,避免進入頁面時「全空」的尷尬。
  2. checkMutex() 處理外部資料髒掉的情況。若 1、3、5 同時為選中,就讓 5 保持選中,1 與 3 歸零。
  3. 點擊時先判斷 !item.isChecked(),避免重複點擊同一項造成不必要的 notifyDataSetChanged()。

4. 使用方式

public class MainActivity extends Activity {

    private GridView mGridLayout;
    private GridRadioAdapter mAdapter;
    private List<RadioItemModel> mItemList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mGridLayout = (GridView) findViewById(R.id.grid_layout);
        initData();

        mAdapter = new GridRadioAdapter(this, mItemList);
        mAdapter.setOnItemCheckedListener(new GridRadioAdapter.OnItemCheckedListener() {
            @Override
            public void onItemChecked(RadioItemModel model, int position) {
                Toast.makeText(MainActivity.this,
                        "已選擇:" + model.getText(), Toast.LENGTH_SHORT).show();
            }
        });
        mGridLayout.setAdapter(mAdapter);
    }

    private void initData() {
        mItemList = new ArrayList<>();
        ColorStateList csl = getResources().getColorStateList(R.color.ddt_color_tab_text);

        mItemList.add(new RadioItemModel("全部", false, true, csl));
        mItemList.add(new RadioItemModel("早餐前", false, true, csl));
        mItemList.add(new RadioItemModel("午餐前", false, true, csl));
        mItemList.add(new RadioItemModel("晚餐前", false, true, csl));
        mItemList.add(new RadioItemModel("早餐後", false, true, csl));
        mItemList.add(new RadioItemModel("午餐後", false, true, csl));
        mItemList.add(new RadioItemModel("晚餐後", false, true, csl));
        mItemList.add(new RadioItemModel("睡前", false, true, csl));
    }
}

把 hiddenRadio 設為 true,圓點消失後它就變成一排漂亮的文字選項卡,拿來切換 Fragment 也很順手:

小結

這套做法的核心觀念是:當容器無法給你想要的行為,就把行為往上提到資料層。 GridView 只負責排列與回收,選中狀態由 RadioItemModel 承載,互斥規則由 Adapter 統一執行。介面怎麼長、要幾欄、要不要圓點,全都只是資料的呈現差異,邏輯一行都不用改。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved