java - 如何在选中 ListItem 后修改它的背景?

标签 java android listview listviewitem

我有一个带有一堆 ListItem 的 ListView。当用户选择一个项目时,我想将该 ListItem 的背景更改为图像。我怎样才能做到这一点?

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> a, View v, int position, long id) {
    // how do I change the ListItem background here?
    }
});

最佳答案

您可以在 ListView 的适配器中设置它。您需要做的是在要返回的 View 上使用 setBackgroundResource。让我举个简单的例子:

// lets suppose this is your adapter (which obviously has
//to be a custom one which extends from on of the main
//adapters BaseAdapter, CursorAdapter, ArrayAdapter, etc.)

// every adapter has a getView method that you will have to overwrite
// I guess you know what I'm talking about
public View getView( args blah blah ){
    View theView;
    // do stuff with the view

    // before returning, set the background
    theView.setBackgroundResource(R.drawable.the_custom_background);

    return theView;
}

请注意,我使用的是 R.drawable.the_custom_background,这意味着您必须编写一些 XML 选择器。别担心,这比听起来容易。在 res/drawable 文件夹中创建一个名为 the_custom_background.xml 的 XML 文件:

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

再次注意,我正在使用 @drawable/the_background_color,所以最后在 res/drawable 文件夹中创建另一个名为 the_background_color 的可绘制对象:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FF0000" />
</shape>

我知道这看起来很乱,但这是 Android 的方式。您也可以尝试修改 setOnItemClickListener 中的 View,但我认为这是不可取的,而且更难实现。

关于java - 如何在选中 ListItem 后修改它的背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3805761/

相关文章:

java - 搜索功能 - 如何将过滤后的数据显示到 ListView 中

java - TreeMap.containsKey() 中的 Werid ClassCastException

java - 创建一个 for 循环等待方法返回 true

android - 如何在 javadoc 中生成指向 android Classes 引用的链接?

android - 使用选择器,形状不会出现在 ImageButton 上

java - Android:在 ListView header 中设置文本

java - IntelliJ - 无法导航到 JDK 目录

java - 使用 Java 搜索文件内容?

java - Android日常工作凌晨12点

listview - 如何在 Xamarin.forms 中自动向下滚动 ListView(MVVM 设计模式)