如何使用带有 ListView 和自定义适配器的选择器来指示所选项目

2024-04-29

我有一个具有 ListView 的活动,并且我创建了一个自定义适配器 基于BaseAdapter。

自定义适配器的 GetView 方法使用自定义布局:

view = context.LayoutInflater.Inflate(Resource.Layout.BluetoothDeviceListItem, null);

布局如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/BluetoothDeviceListSelector">  
  <TextView android:id="@+id/txtBluetoothDeviceName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            style="@android:style/TextAppearance.Large"/>
  <TextView android:id="@+id/txtBluetoothDeviceAddress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            style="@android:style/TextAppearance.Medium"/>
</LinearLayout>

基本上我在下面显示蓝牙设备的名称及其地址。
但我希望用户能够在 ListView 中选择一个项目,并且该项目应该 保持突出显示(至少),或者我可能想为其添加一个图标或其他内容。

据我了解,由于我使用的是自定义布局,因此我丢失了默认选择指示器 并且必须使用我自己的选择器。我在网上教程中发现了这样的内容:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true" >
    <shape>
      <gradient
       android:startColor="#E77A26"
         android:endColor="#1DB38B"
         android:angle="270" />
    </shape>
  </item>
  <item android:state_selected="true">
    <shape>
      <gradient
       android:startColor="#E77A26"
         android:endColor="#2B37AE"
         android:angle="270" />
    </shape>
  </item>
  <item android:state_focused="true">
    <shape>
      <gradient
       android:startColor="#E77A26"
         android:endColor="#EEFFEE"
         android:angle="270" />
    </shape>
  </item>
</selector>

但唯一要做的就是只要用户按住就会改变颜色 ListView 中的一个项目。一旦他放手,一切就不再突出了。

现在我无法弄清楚到底是什么导致了这个问题。

  • 我的 ListView 是否在某个地方失去了选择支持
  • 选择器的 XML 是否完全错误
  • 我应该向适配器添加选择支持(这看起来很奇怪,因为它应该独立于视图)

免责声明:我看过一些相关的问题,但它们并没有真正帮助我。
另外,由于长城的原因,我目前无法访问大部分在线文档


最后,根据@CommonsWare 的评论,我简单地使用了激活状态:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true" >
    <shape>
      <gradient
       android:startColor="#E77A26"
         android:endColor="#1DB38B"
         android:angle="270" />
    </shape>
  </item>
  <item android:state_activated="true">
    <shape>
      <gradient
       android:startColor="#E77A26"
         android:endColor="#EEFFEE"
         android:angle="270" />
    </shape>
  </item>
</selector>

也就是说,我现在已经不再显示所选项目,我只是 单击某个项目后直接导航到新的 Activity,以符合 Android 设计指南。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用带有 ListView 和自定义适配器的选择器来指示所选项目 的相关文章

随机推荐