简体   繁体   中英

Android ListView how to change selected item background

I will ask for help for the following problem. Very strange for me :) I trying to change the background of the selected item in ListView. I set item selected the following way.

drawer_home.setItemChecked(0, true);

I know that I can set the other item background color. I have no problem to change all background or on active item for example but not on selected.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_selected="true" android:drawable="@android:color/holo_blue_light"/>
    <item android:state_checked="true" android:drawable="@android:color/holo_red_dark"/>
    <item android:state_pressed="true" android:drawable="@android:color/holo_green_dark"/>
    <item android:drawable="@android:color/white"/>
</selector>

android:background="@android:color/white"
android:listSelector="@drawable/listview_selector"

What I tried to change is styles on theme and the result is the same. Everything is ok except selected item :(

I found a solution to my problem. I spend an awful lot of time to solve something so simple.

At first look something so simple.

So I will share my experience hopefully save timf another person :) You can simply use.

drawer_home.getChildAt(0).setBackgroundColor(Color.RED);

or

drawer_home.getChildAt(drawer_home.getSelectedItemPosition()).setBackgroundColor(Color.RED);

But only if the item in ListView are static.

And before I met this decision but because dynamically change ListView items with ArrayAdapter.

drawer_home.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_activated_1, home_menu_title));

It gives me an error. Because obviously that content still has not loaded yet. Then use the following.

drawer_home.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
                               int oldTop, int oldRight, int oldBottom) {
        // TODO Auto-generated method stub
        if(menuType == MENU_TYPE_HOME && currentPosition == 0) {
            drawer_home.getChildAt(0).setBackgroundColor(0xCC4d4dff);
        }
    }
});

I do not have much experience with Android so that probably is not the perfect solution.

I will glad of a better solution.

尝试添加

<item android:state_activated="true" android:drawable="@android:color/holo_blue_light"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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