0

I want highlight the first element of my listview programmatically, when the Activity is created.

The highlight options of my ListView are:

<item name="android:choiceMode">singleChoice</item>
<item name="android:listSelector">@color/green</item>

I tried a lot of methods to initialiaze the highlight, all not working.

- list.setSelection();
- list.setItemChecked();
- list.performItemClick();
- maybe other... 

Why is so painfull highlighting a ListView item from code? What I should know?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
optimusfrenk
  • 1,271
  • 2
  • 16
  • 34
  • You could additionally try `View child = listView.getChildAt(0)` and `child.requestFocus()` maybe – OneCricketeer Mar 18 '16 at 16:38
  • Possible duplicate of [Programmatically select item ListView in Android](http://stackoverflow.com/questions/10788688/programmatically-select-item-listview-in-android) – OneCricketeer Mar 18 '16 at 16:40
  • Yes, but what I'm searching is a clean way to highlight. The linked solution (in my opinion) isn't so clean. No? – optimusfrenk Mar 19 '16 at 09:01
  • Do you want a clean solution or a working solution? `Mylistview.setItemChecked(position, true);` isn't clean? – OneCricketeer Mar 19 '16 at 10:36

3 Answers3

0

use custom adapter and in onBindViewHolder user as

if(position == 0){
//set highlight code here
}
Nisar Ahmad
  • 170
  • 1
  • 7
0

Please, check out this

And in getView method add

if(position == 0)
   // set background color for View
Community
  • 1
  • 1
Yurii Kot
  • 316
  • 3
  • 11
0

Add this in your Custom adapter:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
      //Initialize view holder
    switch(position) {
    case 0: {
      //Highlight view
            break;
         }
           default: {
           //Rest of List items
           }
      }
Malwinder Singh
  • 6,644
  • 14
  • 65
  • 103