繁体   English   中英

选择ListItem后,如何修改它的背景?

[英]How can I modify the background of a ListItem when it has been selected?

我有一堆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 res/drawable

<?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 ,但是我认为这是不希望的,并且更难实现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM