我之前通过以下方式手动完成了它:
创建一个数组来保存列表的选定状态,在适配器构造函数中对其进行初始化,然后在您的 getView 方法(以防当前选定的项目滚动出视图)和您的 onItemClick 方法(以更改当前选择并打开关闭旧的)。
public static boolean selectedStatus[]; // array to hold selected state
public static View oldView; // view to hold so we can set background back to normal after
构造 函数初始化数组
public class MyCursorAdapter extends SimpleCursorAdapter {
private LayoutInflater mInflater;
private int layout;
public MyCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
mInflater = LayoutInflater.from(context);
this.layout = layout;
selectedStatus = new boolean[c.getCount()];
for (int i = 0; i < c.getCount(); i++) {
selectedStatus[i] = false; // Start with all items unselected
}
}
}
当孩子滚动出视图时需要getView
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = View.inflate(context, layout, null);
if(selectedStatus[position] == true){
v.setBackgroundResource(R.color.blue);
} else {
v.setBackgroundResource(R.color.black);
}
return v;
}
onItemClick 更改数组和屏幕上的选定项目
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
mRowId = id;
EventDisplayFragment eventdisplay = new EventDisplayFragment();
getFragmentManager().beginTransaction()
.replace(R.id.rightpane, eventdisplay).commit();
if(MyCursorAdapter.oldView != null){
MyCursorAdapter.oldView.setBackgroundResource(R.color.black); // change the background of the old selected item back to default black }
MyCursorAdapter.oldView = v; // set oldView to current view so we have a reference to change back on next selection
for (int i = 0; i < selectedStatus.length; i++) {
if(i == position){ // set the current view to true and all others to false
selectedStatus[i] = true;
} else {
selectedStatus[i] = false;
}
}
}
v.setBackgroundResource(R.color.blue);
return true;
}
});