android - 按下时 GridView 项目不突出显示

标签 android android-layout android-widget

我的应用程序有一个 GridView ,默认情况下,当我点击它时它的项目不会突出显示(我不知道为什么?)。我尝试如下添加列表选择器,但它也不起作用,

<GridView
                android:id="@android:id/list"
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:layout_above="@+id/load_more_process_id"
                android:layout_alignParentTop="true"
                android:drawSelectorOnTop="false"
                android:listSelector="@drawable/grid_selector"
                 >
            </GridView>

这里是我的选择器:

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@android:color/black"></item>
<item android:state_pressed="false" android:drawable="@android:color/white"></item>

最佳答案

如果列表项内容(或每个网格项的 View )中有可聚焦元素,则不会绘制选择器

例如,如果您的列表项的模板是:

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

然后 ListView 将不会为每个 ListView 项绘制选择器,因为默认情况下 CheckBox 是可聚焦的。

您可以为随选择状态变化的每个项目提供背景,或者禁用对所有可聚焦元素的聚焦(这反过来需要您编写一个神奇的适配器来在选择状态变化时检查复选框。

例如:

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

将导致封闭的 ListView 再次开始绘制选择器。

有状态可绘制对象的示例:

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>

然后将其应用于适配器返回的每个 View 的背景:

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

这两种方法都行得通。

列表适配器类(GridView、ListView 和 c)在适配器返回的每个 View 上调用 hasFocusable(),如果 hasFocusable() 返回 true,则禁用选择绘制。幸运的是,它们还将选择/聚焦/按下/Activity 状态复制到当前聚焦或选定的适配器项,因此您可以根据需要自己绘制。

关于android - 按下时 GridView 项目不突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13666012/

相关文章:

android - RTSP 安卓媒体播放器

android - 布局中的一半 ImageView

android - 检测适配器中的滚动方向(上/下)

android - 找不到依赖项 "androidx.core:core-ui"

android - 在 MaterialCardView 中更改拐角半径的问题

android - 在 Android 中创建自定义标题栏

android - 所需的权限常量在 Manifest 类中不可用

android - 后台应用程序会持续接收蓝牙数据包多长时间?

android - 带有 android drawable xml 的光泽渐变

android - 如何在android中单击按钮更新小部件的 View ?