Swapnil
Swapnil

Reputation: 41

List Selector for multicolor list in Android

I am having a list in my android application. The list items are custom objects and depending on the custom object property, list item color will be decided.

Now the problem is, when I select any item for such list, List selector is not displayed.

How can I fix this issue? To set list item color, I am using following method in adapter.

convertView.setBackgroundColor(Color.LTGRAY)

Is this the right way to set color? if not what else I can use.

Thanks in advance.

Swapnil Dalal.

Upvotes: 1

Views: 415

Answers (3)

Swapnil
Swapnil

Reputation: 41

I got solution for this question,

I created to different xml files for different objects in the application. So in the getView of adapter, depending on condition we can load either one of the xml.

Example:

`if(true) {
    convertView.setBackgroundResource(R.drawable.firstxml);
 }
 else {
    convertView.setBackgroundResource(R.drawable.secondxml);
 }`

In these xmls, we can specify colors as required.

Example:

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="false"
        android:drawable="@color/transperent"/>    
    <item
        android:state_pressed="true" 
        android:state_enabled="true"
        android:drawable="@drawable/listview_selector" />
</selector>

Thanks,

Swapnil Dalal.

Upvotes: 0

dreamtale
dreamtale

Reputation: 2913

You can fix this by two ways:

1.Write a selector for the itemview which set the background to the transparent in the pressed state, then set the selector as the backgound of the itemview.

<item android:state_enabled="true"
      android:state_pressed="false"
      android:drawable="@color/gray" />

<item android:state_enabled="true" 
      android:state_pressed="true"
      android:drawable="@color/transparent" />

2.Remove the listselector, just write a selector for the itemview with the color you wanted by the different state and set it as the background of the itemview.

Upvotes: 1

Awais Tariq
Awais Tariq

Reputation: 7754

Please add your getView method code so that we can help you better. One common mistake we do is that we don't always create new view for each item in the list view for loading different layout list Items.

For example common approach for identical itemed list:

if(view == null)
{
    vi = inflater.inflate(R.layout.fb_list_row, parent, false);
}

While for different object listview items you need to remove if statement like this;

vi = inflater.inflate(R.layout.fb_list_row, parent, false);

and then do the changing for each list item..

Hope this will help. Else put some more code.

Upvotes: 0

Related Questions