在 Android 中,我有一个 GridView - GridView 中的每个单元格都是一个 ImageView。当用户单击一个单元格时,我希望该单元格被“选中”(使其背景变为蓝色),并且所有其他单元格“取消选择”(使其背景变为白色)。
我已经实现了以下背景可绘制对象,但它仅在按下单元格时更改背景:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/iconborder_selected" /> <!-- pressed -->
<item android:drawable="@drawable/iconborder_unselected" /> <!-- default -->
</selector>
编辑:这是我的 GridView 适配器代码。
class IconAdapter extends BaseAdapter {
private Context context = null;
private List<Drawable> icons = new ArrayList<Drawable>();
public IconAdapter(Context context) {
this.context = context;
for (Field f : R.drawable.class.getFields()) {
String path = f.getName();
if (path.contains("icon_")) {
int id = context.getResources().getIdentifier(path, "drawable",
context.getPackageName());
Drawable drawable = context.getResources().getDrawable(id);
icons.add(drawable);
}
}
}
@Override
public int getCount() {
return icons.size();
}
@Override
public Object getItem(int position) {
return icons.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView iv = new ImageView(context);
iv.setImageDrawable(icons.get(position));
iv.setBackgroundResource(R.drawable.iconborder);
return iv;
}
}