[Android]讓ListView item被選擇時可以變換背景

看到標題時,一開始以為是個很簡單的問題,結果搞了我一、兩天試了n種方法,都無法解決。後來看了一些文章後,得到了一些解答,首先要明白一點,在觸碰模式下(Touch Mode)下是沒有selection state的,這是android developer blog的說明
In touch mode, there is no focus and no selection.
所以必須想一下有哪些作法,可以騙過android以達到selected的效果,想了想,可能還是要從自訂的layout來下手,果然神人vimalrajpara2006 有解答啦!就是自訂一個CheckAbleLayout來達到ListView有單選的效果,以下是我參考其原始碼修改而來
- 首先自訂一個CheckAbleLayout
package com.example.listview.selected.row;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.LinearLayout;
public class CheckableLayout extends LinearLayout implements Checkable {
private boolean mChecked;
public CheckableLayout(Context context) {
super(context);
}
public CheckableLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setChecked(boolean checked) {
mChecked = checked;
// Use this code for setting custom color in background of this layout
// 當item被點選後,將其背景色改為藍色
setBackgroundDrawable(checked ? new ColorDrawable(android.graphics.Color.BLUE) : null);
// Use this code for setting custom image in background of this layout
/*setBackgroundResource(checked ? R.drawable.ic_action_search
: R.drawable.ic_launcher);*/
}
public boolean isChecked() {
return mChecked;
}
public void toggle() {
setChecked(!mChecked);
}
}
- 再來要將ListView的choiseMode設定為singleChoise
- 最後設定相關的listener
這樣子就大功告成啦!