定制Android ListView颜色?

7

我在网络上搜索了很多有关如何使用列表选择器更改列表视图颜色的帖子。但是这对我似乎没有用。所以我的问题是我做错了什么?

当我使用以下文件时,我得到一个列表,其中所有项目背景最初都是蓝色。(我预期是白色)

当我上下移动焦点时,文本只会变成深灰色,而项目背景仍然是蓝色。(这时我希望单个行为蓝色,其余为白色)

当我点击一行时,我点击的行的背景会变黑,所有其他行会变绿。(我希望我点击的行变为绿色,其余行为白色)

这是我的主要布局文件:

<?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"
    >
<ListView
    android:id="@android:id/list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:listSelector="@drawable/item_selector"
    />
<TextView
    android:id="@android:id/empty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/empty"
    />
</LinearLayout>

这是我的列表项文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:orientation="horizontal" 
    android:padding="10sp">
    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="false"
        />
    <TextView 
        android:id="@+id/title" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:singleLine="true" 
        android:textStyle="bold"
        android:padding="7dip"
        android:textSize="18sp"
        android:layout_toRightOf="@id/checkbox"
        />
</RelativeLayout>

这是我的颜色文件:

<?xml version="1.0" encoding="utf-8"?>
<resources> 
    <color name="red">#ff00</color>
    <color name="green">#f0f0</color>
    <color name="blue">#f00f</color>
    <color name="white">#ffff</color>
</resources>

这是我的选择器文件:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_pressed="true" 
        android:drawable="@color/green" />
    <item 
        android:state_focused="true" 
        android:drawable="@color/blue" />
    <item 
        android:drawable="@color/white" />
</selector>

希望我做错的只是一些愚蠢简单的事情。
提前致谢。

听起来好像整个listView本身被聚焦了,而不是单个列表项。 - YGL
2个回答

7
我认为android:listSelector="@drawable/item_selector"只应用于视图的根部,而不是它所有的子级。
尝试将@drawable/item_selector作为RelativeLayout的背景添加,并在listSelector上放置一个透明布局:android:background="@drawable/item_selector"
android:listSelector="@android:color/transparent"

那是制胜的组合。谢谢!我已经为此苦苦挣扎了几天。 - Ross Hambrick

1

实际上,如果你想在不使用资源的情况下以编程方式完成它,你可以设置元素颜色。例如,在 TextView 中设置文本颜色为 #F123456:

objTextView.setTextColor(color.parseColor("#F12345"));

如果您想在可由用户选择的列表视图中动态设置颜色,这将非常方便,特别是当您需要从数据库中获取颜色列表时,无法使用静态资源文件。


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