How to highlight row in ListView in Android?

I need to highlight the row in the ListView that was selected (to show the user what he selected), so this is not the one that will be selected, this is the one that he selected earlier.

I already have a place:

 ListView.setSelection(position); 

And now I want to select this particular row and select it.

The onCreate() code in action that contains the ListView :

 public class CountryView extends Activity { protected static final String LOG_TAG = null; /** Called when the activity is first created. */ String[] lv_arr = {}; ListAdapter adapter; TextView t; private ListView lvUsers; private ArrayList<Coun> mListUsers; String responce=null; public int d; int selectedListItem = -1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.country); Intent data =getIntent(); mListUsers = getCoun(); lvUsers = (ListView) findViewById(R.id.counlistView); lvUsers.setAdapter(new ListAdapter(this, R.id.counlistView, mListUsers)); selectedListItem=data.getExtras().getInt("PositionInList"); lvUsers.setChoiceMode(ListView.CHOICE_MODE_SINGLE); lvUsers.setOnItemClickListener(new OnItemClickListener() { int positionItem; public void onItemClick(AdapterView<?> parent, View view,int position, long id) { Intent pongIntent = new Intent(getApplicationContext(),Trav.class); int counId=mListUsers.get(position).id; pongIntent.putExtra("response",mListUsers.get(position).p); pongIntent.putExtra("responseCounID",counId); //Put the position of the choose list inside extra positionItem=position; pongIntent.putExtra("PositionInListSet",positionItem); setResult(Activity.RESULT_OK,pongIntent); Log.i("CounID *******************************"," "+counId); finish(); } }); } } 
+34
android android-listview
May 08 '11 at 6:00 a.m.
source share
8 answers

Since ListViews set to NONE by default, in touch mode the setSelection method setSelection not have a visual effect.

To save the previous selection / visual display of the explicit selection, you must first configure the list selection mode accordingly:

 listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 

It is useful to read the API documents for these methods:

  • setSelection
 void android.widget.AdapterView.setSelection(int position) 

Sets the currently selected item. to accessibility subclasses of accessibility that override this method must be called first override the super method.

Parameters :
position The index (starting at 0) of the selected data item.

  • setChoiceMode
 void android.widget.ListView.setChoiceMode(int choiceMode) 

Defines the selection behavior for a List. By default, lists do not have any selection behavior ( CHOICE_MODE_NONE ). By setting selectMode to CHOICE_MODE_SINGLE , the List allows up to one item to be in the selected state. By setting choiceMode to CHOICE_MODE_MULTIPLE , the list allows you to use any number of items to be selected.

Parameters :
choiceMode One of CHOICE_MODE_NONE CHOICE_MODE_SINGLE , or CHOICE_MODE_MULTIPLE

In case this is not enough (let's say you always want to show the last selection differently next to the current selection), you should save your last selected item (the data that populates the ListAdapter ) as lastSelectedItem , and in your adapter the getView method assigns another the background resource to the renderer, if it is equal to this lastSelectedItem .

If your last selection will not be updated when the selection changes, you must explicitly call the notifyDataSetChanged method in your adapter instance.

Refresh
Since your activity containing the ListView is a child of the activity that is waiting for this one result (based on the setResult(Activity.RESULT_OK,pongIntent); part setResult(Activity.RESULT_OK,pongIntent); ), the original idea is correct, the last position should be passed through the intent when the operation starts:

 selectedListItem = getIntent().getIntExtra("PositionInList", -1); lvUsers.setChoiceMode(ListView.CHOICE_MODE_SINGLE); lvUsers.setSelection(selectedListItem); 

ListView.CHOICE_MODE_SINGLE will work if you stay in the same action, but you end it on every itemClick (change of choice), so additional data should be passed to the beginning of the Intent .

You can also set the previously selected background element from your adapter - mentioned above - by overriding its getView method:

 lvUsers.setAdapter(new ArrayAdapter(this, R.id.counlistView, groups) { @Override public View getView(int position, View convertView, ViewGroup parent) { final View renderer = super.getView(position, convertView, parent); if (position == selectedListItem) { //TODO: set the proper selection color here: renderer.setBackgroundResource(android.R.color.darker_gray); } return renderer; } }); 
+37
May 08 '11 at 6:37 a.m.
source share

Simply:

  • Set the correct selection mode in your list. setChoiceMode
  • Set the background to support the selection state in the layout of the elements, for example:

     android:background="?android:attr/activatedBackgroundIndicator" 

FYI:

+27
Jun 19 '13 at 19:10
source share

It is much easier to implement in your layout files and let Android handle the rest ...

1) Make sure you have android:choiceMode="" installed on the ListView layout ( singleChoice , multipleChoice , etc.). The default value is none .

 <ListView android:id="@+id/invite_friends_fragment_contacts_list" android:layout_width="match_parent" android:layout_height="wrap_content" android:choiceMode="multipleChoice"/> <!-- THIS LINE --> 

2) Create an XML file of the state selector and save it in a folder with your capabilities. In this example, we will call it state_selector.xml:

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

3) In the layout of the list of elements, add the file state_selector.xml as the background:

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/state_selector"> <!-- THIS LINE --> <!-- ALL OF YOUR ELEMENTS WILL GO HERE (TextViews, ImageViews, etc) --> </RelativeLayout> 

If you use multipleChoice , you can override onItemClick() and set / uncheck the selected items accordingly . Android will change the background color as specified in state_selector.xml.

+14
Aug 15 '14 at 6:49
source share

I had a problem in finding an easy solution to this, because a large number of manuals and answers contained information about one choice using switches (which were largely based on RadioGroup's).

My problem was that I could set the item to my β€œSelected” state, but then I could not reset the list when the next item was selected. Here is what I came up with:

 listView.setOnItemClickListener(new ItemHighlighterListener ()); 

With this class:

 private class ItemHighlighterListener implements OnItemClickListener{ private View lastSelectedView = null; public void clearSelection() { if(lastSelectedView != null) lastSelectedView.setBackgroundColor(android.R.color.transparent); } @Override public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) { clearSelection(); lastSelectedView = view; view.setBackgroundDrawable(view.getContext().getResources().getDrawable(R.drawable.shape_selected_menu_item)); } } 
+9
Aug 24 '11 at 2:35 a.m.
source share

I solve this problem as follows: 1. set lastClickId by clicking an item in the View list, update the value of lastClickId to the position, and then refresh the background of the view. After that, when we click on one element, this element will be selected, but when we scroll through the listView (make the element that we selected from the screen) and scroll back, the highlight will disappear because the getView () method will repeat in your adapter, therefore we must do the following. 2. in your adapter, change the background in the getView () method, here is the code:

 private static int lastClickId = -1; private OnItemClickListener listener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if ((lastClickId != -1) && (lastClickId != position)) { parent.getChildAt(lastClickId).setBackgroundResource( R.color.grey); view.setBackgroundResource(R.color.blue); } if (lastClickId == -1) { view.setBackgroundResource(R.color.blue); } lastClickId = position; } }; public static int getCurrentSelectedItemId() { return lastClickId; } 

Adapter:

 public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View view = mInflater.inflate(R.layout.tweet_list_layout, null); // set selected item background to blue if (position == MainUserFeedFragment.getCurrentSelectedItemId()) { view.setBackgroundResource(R.color.blue); } } 
+4
Dec 06
source share

Why don't you store the selection in an array, and then pass that array in the constructor of the ListView array adapter, something like myArrayAdapter(context,layoutID,dataArray,selectionArray)

then in your getView method for the array, just do a check. For example, in pseudo code

 if row was previously selected change background color 
+1
May 08 '11 at 7:46
source share

You can use the transition. Follow my code because I made it possible to select a specific list item of choice. Suppose you want to select the first item in 5 seconds.

  if(position == 0){ viewHolderThubnail.relImage.setBackgroundResource(R.drawable.translate); TransitionDrawable transition = (TransitionDrawable) viewHolderThubnail.relImage.getBackground(); transition.startTransition(1000); }else{ viewHolderThubnail.relImage.setBackgroundResource(R.color.white); } 

translate.xml

 <?xml version="1.0" encoding="UTF-8"?> <transition xmlns:android="http://schemas.android.com/apk/res/android"> <!-- The drawables used here can be solid colors, gradients, shapes, images, etc. --> <item android:drawable="@drawable/new_state" /> <item android:drawable="@drawable/original_state" /> </transition> 

new_state.xml

 <?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#92BCE7"/> </shape> 

original_state.xml

 <?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#FFFFFF"/> </shape> 

If you understand this code, which is very simple, I have to say that the list item in the zero position will be highlighted in blue for 5 seconds, and then it will slowly fade to white.

+1
Oct 29 '13 at 12:09 on
source share

SIMPLE of all

 View updatedview=null; @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //these two lines of code means that only one item can be selected at a time if(updatedview != null) updatedview.setBackgroundColor(Color.TRANSPARENT); updatedview=view; Toast.makeText(getApplicationContext(), " " + str[position],Toast.LENGTH_LONG).show(); view.setBackgroundColor(Color.CYAN); } 
0
Mar 02 '16 at 17:04
source share



All Articles