Sandun Jay
Sandun Jay

Reputation: 502

Android - ListView row background color change

I created a ListView with two background color row by row.Then I need to change its background color when click on item and back to its own color loss focusing the item. I tried with below code and view.setBackgroundResource() does not working properly in side the ItemClickListener.

 if (selectedView != null) {
    if (selectedRowIndex % 2 == 0) {
        view.setBackgroundResource(R.color.list_secondcolor);
    } else {
     view.setBackgroundResource(R.color.list_firstcolor);
    }
    }selectedRowIndex = position;
    selectedView = view;view.setBackgroundColor(Color.WHITE);

Is there any other possible way to do it? Thanks in advance.

Upvotes: 0

Views: 4883

Answers (1)

Flo
Flo

Reputation: 27455

You can do this easily via XML. You have to define a drawable with different states. In your case, as the background color of the list items should alternate, you have to define two drawables.

In this drawable you define the color for the different states the list item can have. Normal, focused, pressed, focused and pressed. Then you simply apply this drawable to the background attribute of the list item.

    <?xml version="1.0" encoding="utf-8"?>
        <selector xmlns:android="http://schemas.android.com/apk/res/android">  
            <!-- default -->
            <item android:drawable="@color/normal_color" />
            <!-- focused -->
            <item android:state_focused="true" android:drawable="@color/focused_color" /> 
            <!-- pressed --> 
            <item android:state_pressed="true" android:drawable="@color/pressed_color" />  
            <!-- focused and pressed-->
            <item android:state_focused="true" android:state_pressed="true" android:drawable="@color/focused_pressed_color" />
        </selector> 

Upvotes: 1

Related Questions