Change background color of selected item on a List

2019-01-01 06:48发布

I want to know on how I can change the background color of the selected item on my listView. I only want to change the specific item clicked by the user, meaning if the user clicks another item it will be the one which is highlighted. Well since I want it to keep simple as possible and use the default android listview I used this code instead:

record_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try{
                    for (int ctr=0;ctr<=record_items.length;ctr++){
                        if(i==ctr){
                            record_list.getChildAt(ctr).setBackgroundColor(Color.CYAN);
                        }else{
                            record_list.getChildAt(ctr).setBackgroundColor(Color.WHITE);
                        }
                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                }
                Log.v("Selected item",record_list.getItemAtPosition(i));
            }
        });

Ok this one is working but the problem is that it's slow. Now I want to know if there's any other way around that I can do which will give the same output as I made.

I tried using record_list.getSelectedView().setBackgroundColor(Color.CYAN); but it gives me a null pointer exception.

I also tried the selector.xml but it also didn't do the trick. Furthermore, there is one properties here on ListView which is called listSelector. It's a drawable as said by the documentation "Drawable used to indicate the currently selected item in the list." I also believe that this should do the trick and yes it do the trick on my emulator but not on my galaxy tab. I also tried the other methods but nothing works as I wanted it to be.

16条回答
梦该遗忘
2楼-- · 2019-01-01 07:35

I'm also doing the similar thing: highlight the selected list item's background (change it to red) and set text color within the item to white.

I can think out a "simple but not efficient" way: maintain a selected item's position in the custom adapter, and change it in the ListView's OnItemClickListener implement:

// The OnItemClickListener implementation
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    mListViewAdapter.setSelectedItem(position);
}

// The custom Adapter
private int mSelectedPosition = -1;
public void setSelectedItem (int itemPosition) {
    mSelectedPosition = itemPosition;
    notifyDataSetChanged();
}

Then update the selected item's background and text color in getView() method.

// The custom Adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ...
    if (position == mSelectedPosition) {
        // customize the selected item's background and sub views
        convertView.setBackgroundColor(YOUR_HIGHLIGHT_COLOR);
        textView.setTextColor(TEXT_COLOR);
    } else {
        ...
    }
}

After searching for a while, I found that many people mentioned about to set android:listSelector="YOUR_SELECTOR". After tried for a while, I found the simplest way to highlight selected ListView item's background can be done with only two lines set to the ListView's layout resource:

android:choiceMode="singleChoice"
android:listSelector="YOUR_COLOR"

There's also other way to make it work, like customize activatedBackgroundIndicator theme. But I think that would be a much more generic solution since it will affect the whole theme.

查看更多
只靠听说
3楼-- · 2019-01-01 07:36

use the below xml as listitem background it will solve all the issues. The selected will be highlighted though you scrolled down.

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

Thanks, Nagendra

查看更多
梦寄多情
4楼-- · 2019-01-01 07:38

You can use a selector. Change the colors values and modify the below according to your needs.

bkg.xml in drawable folder

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

pressed.xml in drawable folder

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<solid android:color="#FF1A47"/>  // color   
<stroke android:width="3dp"
        android:color="#0FECFF"/> // border
<padding android:left="5dp"
         android:top="5dp"
         android:right="5dp"
         android:bottom="5dp"/> 
<corners android:bottomRightRadius="7dp" // for rounded corners
         android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp"
         android:topRightRadius="7dp"/> 
</shape>

normal.xml in drawable folder

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<solid android:color="#FFFFFF"/>    
<stroke android:width="3dp"
        android:color="#0FECFF" />

<padding android:left="5dp"
         android:top="5dp"
         android:right="5dp"
         android:bottom="5dp"/> 
<corners android:bottomRightRadius="7dp"
         android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp"
         android:topRightRadius="7dp"/> 
</shape>

Set the background drawable to listview custom layout to be inflated for each row

I recommend using a custom listview with a custom adapter.

  android:background="@drawable/bkg"     

If you have not used a custom adapter you can set the listselector to listview as below

   android:listSelector="@drawable/bkg" 
查看更多
心情的温度
5楼-- · 2019-01-01 07:38

Simplest way I've found:

in your activity XML add these lines:

<ListView 
... 
android:choiceMode="singleChoice"
android:listSelector="#666666"
/>

or programatically set these properties:

listView.setSelector(Drawable selector)
listView.setSelector(int resourceId)

My particular example:

   <ListView
            android:choiceMode="singleChoice"
            android:listSelector="#666666"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/listView"/>

thanks to AJG: https://stackoverflow.com/a/25131125/1687010

查看更多
步步皆殇っ
6楼-- · 2019-01-01 07:38

assume you want one item to be clicked each time. Then this code works well. Let's take the listview name as stlist

stList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        // here i overide the onitemclick method in onitemclick listener
            public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            //color change
            //selected item colored

            for(int i=0; i<stList.getAdapter().getCount();i++)
            {
                stList.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
            }

            parent.getChildAt(position).setBackgroundColor(Color.GRAY);

    });
查看更多
时光乱了年华
7楼-- · 2019-01-01 07:40

You can keep track the position of the current selected element:

    OnItemClickListener listViewOnItemClick = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
                mSelectedItem = position;
                mAdapter.notifyDataSetChanged();
        }
    };

And override the getView method of your adapter:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final View view = View.inflate(context, R.layout.item_list, null);

        if (position == mSelectedItem) {
            // set your color
        }

        return view;
    }

For me it did the trick.

查看更多
登录 后发表回答