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

buk*_*.wh 5 android listview

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

T.V*_*.V. 8

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

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

android:listSelector="@drawable/list_selector"
Run Code Online (Sandbox Code Playgroud)

然后在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>
Run Code Online (Sandbox Code Playgroud)

@绘制/ 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>
Run Code Online (Sandbox Code Playgroud)

@绘制/ 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>
Run Code Online (Sandbox Code Playgroud)

在ListView选择中

listView.setOnItemClickListener(new OnItemClickListener() {

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

不要忘记将list_background_pressedlist_background添加到values/color.xml中,或者只是在每个文件中手动设置颜色.

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

希望能帮助到你.