Highlighting a listView item when app starts

346 views Asked by At

I want to have the first item on my listView selected when the app runs and the menu is opened for the first time (without the need of clicking). Can anyone help me? I would also like to be able to draw a small vertical line on the right border of the selected item to highlight it, but I couldn't find another way to highlight an item other than changing the background...

enter image description here

The xml regarding the listView:

<ListView
    android:id="@+id/slider_list"
    android:layout_width="240dp"
    android:layout_height="186dp"
    android:layout_gravity="start"
    android:background="#368ee0"
    android:textColor="#ffffff"
    android:choiceMode="singleChoice"
    android:listSelector="#44444444"
    android:divider="#b0e0e6"
    android:dividerHeight="1dp" />

Edit 1:

In my MainActivity I am trying to follow one of the suggestions and set the background color of the item before displaying the contents. The relevant lines are:

private ListView mDrawerList;
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();//which for instance i use as String url = rowItems.get(position).getPageUrl();

mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());

And after I am trying something like this:

((RowItem)mDrawerList.getItemAtPosition(0)).setBackgroundColor(Color.rgb(68, 68, 68));

But rowItems do not have a setBackgroundColor method. I should get the item from the listView (mDrawerList), but is filled with RowItems.

2

There are 2 answers

5
Vivek Khare On BEST ANSWER
 if (position == selectedListItem)
  {
    //TODO: set the proper selection color here:
    renderer.setBackgroundResource(android.R.color.darker_gray);
  } 


     try this you can just update zeroth position element to always set a different color 
1
Akhil On

What you can try is

list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

list.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
        view.setSelected(true);
        ...
    }
}

After using this mode you can specify different backgrounds using selectors.