【问题标题】:Android - Make a custom view selectable in a ListViewAndroid - 使自定义视图在 ListView 中可选
【发布时间】:2016-07-21 17:07:39
【问题描述】:

所以我有一个 ListView,呈现自定义视图(每个都有图像 + 文本)。 我希望这些视图在用户选择它们时具有不同的外观。 (有一个覆盖,但现在我试着让它只在背景下工作)

如果我用Android.Resource.Layout.TestListItem 填充一行,它会起作用,当我单击时,单元格会显示选定状态。

但是,我尝试使用自定义布局获得类似的效果,但无法正常工作。是不是少了什么?

我有这个视图布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/rowbackground">

... (textview and image)

和 rowbackground.xml:

<?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/bg_a" />
<item android:state_checked="true" android:drawable="@drawable/bg_b" />
<item android:state_pressed="true" android:drawable="@drawable/bg_c" />
<item android:state_selected="false" android:state_checked="false" android:state_pressed="false" android:drawable="@drawable/bg_d"/>
</selector>

但唯一有效的两个状态是“默认”和“按下”状态。不是“选定”的。 (我也尝试过检查,正如我在一些示例中看到的那样)

如何使我的自定义布局视图可选择?

【问题讨论】:

  • 为什么 android.R.layout.test_list_item 起作用可能是因为 test_list_item 是 TextView 而你的布局是 LinearLayout,
  • 尝试将 android:focusable="false" 添加到您的 LinearLayout,或者仅使用 TextView 作为您的布局并使用其属性 leftDrawable 在 TextView 的左侧显示图像,这样更方便只有一个 TextView 和一个 Image。
  • 谢谢。可能是这样,但是是什么使 TextView 可选择而不是 LinearLayout ?我尝试添加 android:focusable="false" 但它没有改变。

标签: android listview xamarin.android


【解决方案1】:

实际上,要在列表视图中处理“已选择”状态,您必须使用 激活 选择器 (android:state_activated),例如:

<item android:state_activated="true" android:drawable="@drawable/ic_dep" />

当然,这似乎没有在任何地方记录。但是,为什么这么简单?谢谢安卓

【讨论】:

    【解决方案2】:

    在 ListView android:background="@drawable/rowbackground" 中添加此行,不要从自定义布局中删除此行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多