Grid view item not hightlight when press

早过忘川 提交于 2019-12-03 16:05:44

If you have a focusable element in the list item contents (or the views for each grid item), the selector isn't drawn

For example, if the template for your list items is:

<LinearLayout android:orientation="horizontal" ... >
    <CheckBox android:id="@+id/checkBox" ... />
    <TextView android:id+"@+id/textView" ... />
</LinearLayout>

then ListView will not draw a selector for each ListView item, because the CheckBox is, by default, focusable.

You can either provide a background on each item that changes with selection state, or disable focus on all focusable elements (which in turn requires you to write a fairy fancy adapter to check the checkboxes when selection state changes.

eg:

<CheckBox android:id="@+id/checkBox" android:focusable="false" ... />

will cause an enclosing ListView to start drawing the selector again.

Example of a stateful drawable:

drawable/my_list_selector_bg.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/list_background_pressed"
        android:state_pressed="true" />
    <item android:drawable="@drawable/list_background_focused"
        android:state_focused="true" />
    <item android:drawable="@android:color/transparent" />
 </selector>

You then apply that to the background of each view returned by your adapter:

<LinearLayout android:orientation="horizontal" 
      android:background="@drawable/my_list_selector_bg"
  ... >

Either approach will work.

The list adpater classes (GridView, ListView, &c) call hasFocusable() on each view returned by the adapter, and disable selection drawing if hasFocusable() returns true. Fortunately, they also replicate the selection/focus/pressed/active state to the currently focused or selected adapter item, so you can draw it yourself if you want.

For those of you who are having the same issue I was, try

gridView.setDrawSelectorOnTop(true);

I have an ImageView and a TextView in each of my GridView items. My selector was working, but it was drawing behind my image.

  1. Layout of grid view:

     <GridView xmlns:android="http://schemas.android.com/apk/res/android" 
     android:listSelector="@drawable/gridselector"/>
    
  2. Create custom selector gridselector.xml like:

    <selector xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/selector_item">
       <item 
         android:state_pressed="true" 
         android:drawable="@drawable/focus_offfocus">
      </item>
    
       <item 
          android:state_enabled="true" 
          android:state_focused="true" 
          android:drawable="@drawable/focus_onfocus">
      </item>
    
      <item android:state_enabled="true" 
        android:drawable="@drawable/focus_offfocus">
      </item> 
    </selector>
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!