【问题标题】:Android ListView. How to change background color of manually selected item安卓列表视图。如何更改手动选择项目的背景颜色
【发布时间】:2014-01-21 08:58:00
【问题描述】:

请你帮帮我。我需要更改由 setSelection(int pos) 函数手动选择的列表视图项的背景颜色,并且在新的 setSelection 调用之前我需要保持新颜色。我已经阅读了一些关于如何做到这一点的主题,但我仍然没有成功。谢谢!

【问题讨论】:

  • 尝试使用listSelector 作为here
  • 你的项目是被点击选中的吗?如果是,您可以使用 listView 中的 onItemClick
  • 不,我正在通过 setSelection(int pos) 函数手动选择我的项目。
  • 你的列表项是对象吗?

标签: android listview


【解决方案1】:

我已经设法通过为不同的状态制作几个选择器来实现这一点

首先把它放在你的列表视图中

android:listSelector="@drawable/list_selector"

然后在drawable中创建xml文件来控制不同的状态

@drawable/list_selector

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/list_item_bg_normal" android:state_activated="false"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_activated="true"/>
</selector>

@drawable/list_item_bg_normal

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
  android:startColor="@color/list_background"
  android:endColor="@color/list_background"
  android:angle="90" />
</shape>

@drawable/list_item_bg_pressed

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="@color/list_background_pressed"
      android:endColor="@color/list_background_pressed"
      android:angle="90" />
</shape>

在您的 ListView 选择中

listView.setOnItemClickListener(new OnItemClickListener() {

         @Override
         public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
             view.setSelected(true);
             ...
         }
    }

不要忘记将 list_background_pressedlist_background 添加到您的 values/color.xml 或在每个文件中手动设置颜色。

而且我相信,当您使用 setSelection(int pos) 时,它会自动使用您设置为选中的布局。

希望对你有帮助。

【讨论】:

  • 谢谢!我照你说的做了,还是没有成功((
  • 我已经使用 setOnItemClickListener 方法编辑了我的代码,请检查一下。
  • 谢谢!我会试试看!如果我错了,请纠正我:函数 setSelection 会自动调用我的列表视图的 onItemClick 方法?
  • 是的,我相信确实如此。如果您不成功,也请查看此帖子stackoverflow.com/questions/4800415/…
  • 我照你说的做了,但什么也没发生((((。谢谢你的链接,我会检查她。可能会有所帮助))
【解决方案2】:
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (updateview != null) updateview.setBackgroundColor(Color.TRANSPARENT);
        updateview = view;
        view.setBackgroundColor(Color.CYAN);
    }
});

【讨论】:

    猜你喜欢
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多