1

在 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;
    }

}
4

2 回答 2

2

您还应该添加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>
于 2013-05-12T20:43:25.863 回答
2

尝试在 XML 声明中GridView放置这些行:

<GridView
 <!-- Some stuff here, like id, width, e.t.c. -->
 android:drawSelectorOnTop="true"
 android:listSelector="path_to_your_selector"
/>

你的选择器应该包含这样的内容:

<item android:state_pressed="true">
    <shape>
        <!-- Or a drawable here -->
    </shape>
</item>
<item android:state_focused="true">
    <shape>
        <!-- Or a drawable here -->
    </shape>
</item>
<item android:drawable="@android:color/transparent" />
于 2013-05-13T14:52:15.300 回答