Android ListView。如何更改手动选定项目的背景颜色

时间:2014-01-21 08:58:00

标签: android listview

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

2 个答案:

答案 0 :(得分:8)

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

首先将其放入listview

android:listSelector="@drawable/list_selector"

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

<强> @绘制/ 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>

<强> @绘制/ 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>

<强> @绘制/ 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_pressed list_background 添加到您的values / color.xml中,或者只是在每个文件中手动设置颜色。

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

希望它有所帮助。

答案 1 :(得分:0)

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);
    }
});
相关问题