Android GridView 单元格颜色背景

Android GridView cell color Background

如果GridView的单元格被按下,我想改变背景颜色。我创建的代码有效,但是当按下另一个单元格时,所选单元格必须更改颜色,所有其他单元格不得有任何背景颜色。 感谢您的帮助。

 elenco_ore.setOnItemClickListener(new OnItemClickListener() {
             public void onItemClick(AdapterView<?> parent, View v,
                                     int position, long id) {

                 List<String> lList = Arrays.asList(orari);
                 Iterator<String> iterator = lList.iterator();
                 while (iterator.hasNext()) {
                     String orari_array = (iterator.next());
                     if(orari_array != (((TextView) v).getText())){
                     ((TextView) v).setBackgroundColor(Color.RED);
                 }else{
                     ((TextView) v).setBackgroundColor(Color.TRANSPARENT);

                     }
                 }

             }
         });

您可以将单选的网格视图修改为-

<GridView
       ...
       android:choiceMode="singleChoice" />

选择器为

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_focused="true"
          android:drawable="@drawable/grid_item_pressed" />
    <item android:state_pressed="true"
          android:drawable="@drawable/grid_item_pressed" />
    <item android:state_selected="true"
          android:state_activated="true"
          android:drawable="@drawable/grid_item_selected" />
    <item android:state_activated="true"
          android:drawable="@drawable/grid_item_selected" />
    <item android:state_selected="true"
          android:drawable="@android:color/black" />
    <item android:drawable="@android:color/transparent" />
</selector>

无需担心其他事情 android 会自动管理项目的状态。