Search code examples
androidstateadditiondrawablestates

different color for certain item in my list


I have a list with items, some items can be in 'viewed' status. i want those items to have different background color then the rest.

list view basically has a single selector for the whole list, setting a background color on one of the items prevent wont do the trick since the selector is drawn below my item's layout as background and counts on them being transparent.

is there a way to define more then one selector for a list ? if not is it possible to create a selector that has an extra state ? basically all i want is the regular list selector plus an extra state that it's ColorDrawable is defined in my colors.xml.(since i can't inherit from a drawable and the list_selector drawables of android are not visible in the SDK for me to use i wanted just to add a state, but then how do i enforce using the extra state ?)


Solution

  • Found the answer. My problem is not the state of the selector, i want the selector in the same state for ALL items! the problem is that i want the item to be regular if certain boolean in items in the adapter is false and color X if the boolean is true, but even if the color is X i still want it to be transparent once it's selected or pressed.

    So the solution is the following xml:

        <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true" 
              android:drawable="@android:color/transparent" /> <!-- pressed -->
        <item android:state_selected="true" 
              android:drawable="@android:color/transparent" /> <!-- focused -->
        <item android:drawable="@color/viewed_hotels_color" /> <!-- default -->
    </selector>
    

    i found out the even though the list itself is the one that gets the state , it DOES pass the state on to it's children (I.E the list items) which i thought it didn't do. Only android:focused wont be effective here, android list items are not focused but selected... so as you can see in any state that is not pressed or selected i give my default color, otherwise it's transparent and the selector is visible to all.

    in my adapter i need the following code(in getView() method):

    View itemView = convertedView; <- i'll spare you the layout details...
    Item item = getItem(position);
    if( item.isViewed() ){
        itemView.setBackgroundResource(R.drawable.viewed_item_background);
    }else{
        itemView.setBackgroundDrawable(null);
    }
    

    this makes sure every item will get the right background. of course if an item state is changed to viewed and i want it to show i need to call notifyDatasetCahnged() on the adapter.