如何在Android列表项点击或选择时更改颜色?

11

可能是重复问题:
如何在 Android 的 ListView 中更改列表项的颜色

各位朋友,

我想在 Android 列表项点击时更改其颜色,有没有人能指导我需要使用哪个属性来实现这个功能?

事实上,当用户点击列表项时,他不知道它是否被点击了。

以下是我的代码:

<ListView android:id="@+id/android:list" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:drawSelectorOnTop="false"
        android:layout_below="@+id/Tablayoutdesign"
        android:cacheColorHint="#000000"
        android:dividerHeight="1dip"
        android:layout_marginTop="63dip"
        android:layout_marginBottom="40dip"
        />

我已经编辑了我的回答,请参考。 - Sankar Ganesh PMP
你好Umar,我也遇到了和你一样的问题。你是怎么解决的?能分享一下吗?谢谢。 - SRam
1个回答

27

步骤1:将android:listSelector属性嵌入您的ListView中,如下所示。

<ListView android:id="@+id/android:list" android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_below="@+id/Tablayoutdesign"
        android:cacheColorHint="#000000"
        android:dividerHeight="1dip"
        android:layout_marginTop="63dip"
        android:layout_marginBottom="40dip"

        />

步骤2:创建一个名为listselector的新xml文件,并将以下代码放入其中

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

  <!-- Selected --> 
  <item 
    android:state_focused="true" 
    android:state_selected="false" 
    android:drawable="@drawable/focused"/> 

  <!-- Pressed -->
  <item 
    android:state_selected="true" 
    android:state_focused="false"
    android:drawable="@drawable/selected" /> 

</selector> 

步骤3:创建一个名为colors.xml的文件,将以下代码添加到该文件中

<resources>
    <drawable name="focused">#ff5500</drawable>
    <drawable name="selected">#FF00FF</drawable>
</resources>

在你的Java代码中添加这一行

ListView lv= (ListView) findViewById(R.id.list);
lv.setSelector( R.drawable.listselector);

1
@UMMA:在drawable文件夹中创建list_selector.xml文件,并在values文件夹下创建color.xml文件。 - Sankar Ganesh PMP
这对我也没用。 - Yashpal Singla
"@drawable/focused" 是什么样子? - IgorGanapolsky
对我不起作用 :( - Android Dev
除了使用lv.setSelector(R.drawable.listselector)的方式之外,你还可以使用android:listSelector="@drawable/listselector"。看起来更加简洁 ;) - Tuss
显示剩余17条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接