Question

I have a menu drawer with a list that has a custom ArrayAdapter. I wish to change the background color of a selected list item but I'm not sure how to. I tried changing it in my getView of the adapter, like how some others have suggested, but that didn't work, the background color is still unchanged.

Here's what I tried:

public View getView(int position, View convertView, ViewGroup parent) {
  View myView = getItem(position).getView(mInflater, convertView);
  if (myView.isSelected())
    myView.setBackgroundColor(Color.BLACK);
  return myView;
}

Where should I be doing this, and how?

Thanks.

Was it helpful?

Solution

You can do this just using selector as below...

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="#FFFFFF" android:state_activated="false"/>
    <item android:drawable="#000000" android:state_pressed="true"/>
    <item android:drawable="#000000" android:state_activated="true"/>

</selector>

And then use this selector as background of your list item layout as below...

<?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="48dp" 
    android:background="@drawable/list_selector">

    ........
    ........

<RelativeLayout/>

OTHER TIPS

@Override
public View getView (int position, View convertView, ViewGroup parent){
    if(matchPosition.contains(new Integer(position))){
        TextView mvw = (TextView)super.getView(position, convertView, parent);
        mvw.setBackgroundColor(getResources().getColor(R.color.litegreen));
    }
    return super.getView(position, convertView, parent);
}

i use the above on entries in a list and working fine

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top