Change the background color of a selected item in a ListView

I want to know how to change the background color of a selected item in my View list. I only want to change the specific element clicked by the user, that is, if the user clicks on another element, it will be selected. Well, since I want it to be as simple as possible and use the default list for Android, I used this code:

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 works, but the problem is that it is slow. Now I want to know if there is another way that I can do that will give the same result as me.

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

I also tried selector.xml but also did not. In addition, there is one object in the ListView called listSelector. This can be done according to the Drawable documentation used to indicate the currently selected item in the list. I also believe that this should do the trick, and yes, it does the trick on my emulator, but not on my galaxy tab. I also tried other methods, but nothing works as I would like.

+52
android android-layout
Jun 07 '13 at 4:51 on
source share
15 answers

You can track the position of the currently selected item:

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

And override your adapter's getView method:

  @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; } 

This is a trick for me.

+71
Jun 07 '13 at 7:03 on
source share

You can use the selector. Change the color values ​​and change below according to your needs.

bkg.xml in moveable 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> 

clicked .xml in the folder with the ability to transfer

 <?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 the folder with the ability to transfer

 <?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> 

Sets the background output for a custom listview layout to pump for each row

I recommend using a custom list with a custom adapter.

  android:background="@drawable/bkg" 

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

  android:listSelector="@drawable/bkg" 
+67
Jun 07 '13 at 5:00
source share

Define a variable

 private ListView mListView; 

Initialize variable

 mListView = (ListView)findViewById(R.id.list_view); 

OnItemClickListener View List

  mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adpterView, View view, int position, long id) { for (int i = 0; i < mListView.getChildCount(); i++) { if(position == i ){ mListView.getChildAt(i).setBackgroundColor(Color.BLUE); }else{ mListView.getChildAt(i).setBackgroundColor(Color.TRANSPARENT); } } } }); 

Create and run a project - Done

+23
May 5 '15 at 10:49
source share

If you want the item to remain selected after you clicked it, you need to manually set it as selected in the onItemClick listener

The Android ListView Favorite List item is highlighted :

 myList.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { view.setSelected(true); // <== Will cause the highlight to remain //... do more stuff }}); 

It is assumed that your selector has a state_selected element:

 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_enabled="true" android:state_pressed="true" android:drawable="@color/red" /> <item android:state_enabled="true" android:state_focused="true" android:drawable="@color/red" /> <item android:state_enabled="true" android:state_selected="true" android:drawable="@color/red" /> <item android:drawable="@color/white" /> </selector> 
+15
Sep 25 '13 at 23:14
source share

Method 1:

Refresh ListView in your activity / xml layout fragment:

 <ListView ... android:choiceMode="singleChoice" android:listSelector="@android:color/darker_gray" /> 

To this, everything is ready!

If you want a programmatic way to handle this, use method 2 ...

Method 2:

If you use ListFragment, you can override onListItemClick () using the view to set the color. Save the current view selected in the reset color of the last selection.

Please note that this only works on lists that fit on one screen, as the viewing has been redesigned.

 public class MyListFragment extends ListFragment { View previousSelectedItem; ... @Override public void onListItemClick(ListView parent, View v, int position, long id) { super.onListItemClick(parent, v, position, id); if (previousSelectedItem!=null) { previousSelectedItem.setBackgroundColor(Color.WHITE); } previousSelectedItem=v; v.setBackgroundColor(Color.BLUE); } } 
+7
Jun 22 '16 at 21:20
source share

First you can create an XML selector file, as shown below, in your drawable/list_item_selector.xml

 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_activated="true"> <shape android:shape="rectangle"> <solid android:color="#333333" /> <padding android:left="5dp" android:right="5dp" /> </shape></item> <item><shape android:shape="rectangle"> <solid android:color="#222222" /> </shape></item> </selector> 

And then in your list, indicate the background as

 android:background="@drawable/list_item_selector" 
+6
Jun 07 '13 at 5:46 on
source share

For those who wonder what EXACTLY needs to be done to save the selected lines, even when you scroll down. This is state_activated . The rest will take care of the internal functionality, you do not need to worry about switching and select multiple items. I did not need to use the notifyDataSetChanged () or setSelected (true) methods.

Add this line to your selector file, for me drawable \ row_background.xml

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

Then in the layout \ custom_row.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dip" android:background="@drawable/row_background" android:orientation="vertical"> <TextView android:id="@+id/line1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> 



For more information, I use this with the ListView adapter, using myList.setChoiceMode (ListView.CHOICE_MODE_MULTIPLE_MODAL); as well as myList.setMultiChoiceModeListener (new MultiChoiceModeListener () ...

from this example: http://www.androidbegin.com/tutorial/android-delete-multiple-selected-items-listview-tutorial/

In addition, you should use this structure to connect to the adapter list: List myList = new ArrayList ();

instead: ArrayList myList = new ArrayList ();

Explanation: Type List and ArrayList Type in Java

+6
Feb 25 '17 at 18:21
source share

The easiest way I've found:

in your XML activity add the following lines:

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

or programmatically set these properties:

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

My specific example:

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

thanks AJG: stack overflow

+3
May 16 '16 at 6:49
source share

use the below xml as a background listitem, it will solve all problems. Selected ones will be highlighted when scrolling 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

+2
Nov 28 '14 at 10:10
source share

I also do a similar thing: select the selected item in the list of items (change it to red) and set the text color inside the item to white.

I can come up with a β€œ simple but not effective ” way: save the selected position of the position in the user adapter and change it in the implementation of the ListView OnItemClickListener :

 // 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 background and text color in the getView() method.

 // The custom Adapter @Override public View getView(int position, View convertView, ViewGroup parent) { ... if (position == mSelectedPosition) { // customize the selected item 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 setting android:listSelector="YOUR_SELECTOR" . After some time, I found the easiest way to select the selected ListView item, which can be done with only two lines set to the ListView layout resource:

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

There is another way to make it work, for example, customizing the activatedBackgroundIndicator theme. But I think it will be a much more general solution, as it will affect the whole topic.

+2
Dec 15 '15 at 6:51
source share

I know this is an old question, but I give a simple solution for this need (without loops!):

 //On your adapter create a variable: private View lastSelectedItem; //Define the folowing method: private void toggleBackgroundItem(View view) { if (lastSelectedItem != null) { lastSelectedItem.setBackgroundColor(Color.TRANSPARENT); } view.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark)); lastSelectedItem = view; } //finally invoque the method onItemClick lvSac.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick (AdapterView < ? > adapterView, View view,int i, long l){ toggleBackgroundItem(view); } } 
+2
Mar 11 '17 at 13:04 on
source share

Suppose you want each item to be pressed each time. Then this code works well. Take the list 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); }); 
+1
May 09 '15 at 3:48
source share

This is a simple method that can handle the selection, even if the list is long:

 public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder=new Holder(); View rowView; rowView = inflater.inflate(R.layout.list_item, null); //Handle your items. //StringHolder.mSelectedItem is a public static variable. if(getItemId(position)==StringHolder.mSelectedItem){ rowView.setBackgroundColor(Color.LTGRAY); }else{ rowView.setBackgroundColor(Color.TRANSPARENT); } return rowView; } 

And then in your onclicklistener:

 list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { StringHolder.mSelectedItem = catagoryAdapter.getItemId(i-1); catagoryAdapter.notifyDataSetChanged(); ..... 
+1
Jun 29 '16 at 7:29
source share
  View updateview;// above oncreate method listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override `enter code here`public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (updateview != null) updateview.setBackgroundColor(Color.TRANSPARENT); updateview = view; view.setBackgroundColor(Color.CYAN); } }); 
+1
Jul 15 '16 at 22:36
source share

In the ListView set:

 android:choiceMode="singleChoice" 

Create a background selector (drawable / selector_gray.xml):

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

Add list item:

 <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="5dp" android:background="@drawable/selector_gray" android:textColor="@color/colorPrimary" tools:text="Your text" /> 

In ViewHolder you can inflate this element.

0
Aug 30 '17 at 18:17
source share



All Articles