设置列表项的背景

时间:2016-01-30 21:32:13

标签: android listview background onitemclicklistener

当我点击listView的项目时,我点击的其他项目的背景会发生变化。如果我点击第一个,那么ListView的背景和ListView的最后一项正在改变。如果我向下滚动并单击某个项目,则单击该项目后的项目会更改其颜色。我该怎么做才能更改所选项目的背景?

XML:

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/lvPlace"/>

爪哇:

lvPlace=(ListView) findViewById(R.id.lvPlace);
lvPlace.setAdapter(placeAdapter);
lvPlace.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            lvPlace.getChildAt(position).setBackgroundColor(myColors[0]);
        }
    });

2 个答案:

答案 0 :(得分:1)

单击xml

时,您可以设置列表项的背景

首先将android:listSelector添加到listview

<ListView
    android:id="@+id/lv"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_marginLeft="6dp"
    android:layout_marginRight="6dp"
    android:divider="@android:color/transparent"
    android:dividerHeight="4.0sp"
    android:listSelector="@drawable/list_row_selector"/>

现在在drawables中创建list_row_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/list_row_bg" android:state_pressed="false" android:state_selected="false"/>
<item android:drawable="@drawable/list_row_bg_hover" android:state_pressed="true"/>
<item android:drawable="@drawable/list_row_bg_hover" android:state_pressed="false" android:state_selected="true"/>

list_row_bg.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>

<gradient
    android:startColor="#ffffff"
    android:centerColor="#ffffff"
    android:endColor="#ffffff"
    android:angle="270" />

list_row_bg_hover.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<gradient
    android:startColor="#18d7e5"
    android:centerColor="#16cedb"
    android:endColor="#09adb9"
    android:angle="270" />

希望这对你有用.. !!

答案 1 :(得分:0)

您可以跟踪商品的位置。

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        for (int j = 0; j < adapterView.getChildCount(); j++)
            adapterView.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);

        // Change the background color of the selected element 
        //to your desire color
        view.setBackgroundColor(Color.BLUE);
});
相关问题