RadioButton 在 App 開發中非常常見。但系統預設的外觀既死板又處處可見,為了讓介面「與眾不同」,通常都要自訂圖示。以下分享我的實作方式:用 ImageView 與 TextView 組合成一個自訂控制項。
/**
* 組合控制項
*/
public class RadioButton extends LinearLayout {
private Context context;
private ImageView imageView;
private TextView textView;
private int index = 0;
private int id = 0; // 是否選中
private int state[] = { R.drawable.radio_unchecked,
R.drawable.radio_checked };
/** 切換圖片 */
public void ChageImage() {
index++;
id = index % 2; // 取得圖片 id
imageView.setImageResource(state[id]);
}
/** 設定文字 */
public void setText(String text) {
textView.setText(text);
}
public String getText() {
return id == 0 ? "" : textView.getText().toString();
}
public RadioButton(Context context) {
this(context, null);
}
public RadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
LayoutInflater.from(context).inflate(R.layout.item, this, true);
imageView = (ImageView) findViewById(R.id.iv_item);
textView = (TextView) findViewById(R.id.tv_item);
}
}
概念很單純:以 index % 2 在兩張圖之間反覆切換,達到勾選/取消的效果。
public class MainActivity extends Activity {
ListView listView;
RadioButton temp; // 記錄上一次點擊的物件
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.lv_main);
listView.setAdapter(new MyAdapter(this));
}
class MyAdapter extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
public MyAdapter(Context context) {
super();
this.context = context;
inflater = LayoutInflater.from(context);
}
@Override public int getCount() { return 10; }
@Override public Object getItem(int position) { return null; }
@Override public long getItemId(int position) { return 0; }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
RadioButton radioButton;
if (convertView == null) {
radioButton = new RadioButton(context);
} else {
radioButton = (RadioButton) convertView;
}
radioButton.setText(position + "");
radioButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 若已有被選中的物件,先取消它
if (temp != null) {
temp.ChageImage();
}
temp = radioButton;
radioButton.ChageImage();
Toast.makeText(context, radioButton.getText(), 1000).show();
}
});
return radioButton;
}
}
}
邏輯是:以 temp 記住上次點擊的物件;點擊時先判斷 temp 是否為 null,不為 null 就呼叫 temp.ChageImage() 取消它的選中狀態,再切換目前這個,最後別忘了把目前的物件指派給 temp。
只有 10 筆資料時一切正常,但換成 20 筆就會出現詭異現象——第 15 筆會自動被勾選。原因出在 ListView 的 convertView 重用機制:螢幕外被回收的 View 會被拿來重複使用,於是先前設定的選中狀態被一起帶了過來。
解法是在 getView 中每次都重置狀態,不要依賴 View 目前的外觀;也就是把 radioButton.setChecked(...) 這類還原動作放在 if/else 之後、設定監聽器之前,讓每一列的初始狀態都由 position 明確決定。這樣不論 convertView 是否被重用,畫面都會正確。