在 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;
}
}
最佳答案
您还应该添加 state_selected
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
android:drawable="@drawable/iconborder_selected" /> <!-- selected -->
<item android:state_pressed="true"
android:drawable="@drawable/iconborder_pressed" /> <!-- pressed -->
<item android:state_pressed="false"
android:drawable="@drawable/iconborder_unselected" /> <!-- default -->
</selector>
关于android - 如何确保更改所选 GridView 单元格的背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16511733/