Nitesh Kabra
Nitesh Kabra

Reputation: 509

How to change selected row background color in Android?

I want to set background color on list view item on when a click is done. A custom adapter is used for list view in Android

Upvotes: 2

Views: 2201

Answers (3)

Ramkailash
Ramkailash

Reputation: 1850

<item android:state_activated="true">
  <shape android:shape="rectangle">
    <solid android:color="#333333" />
    <padding android:left="5dp" android:right="5dp" />
  </shape></item>
<item><shape android:shape="rectangle">
        <solid android:color="#222222" />
    </shape></item>

Upvotes: 0

Zohaib
Zohaib

Reputation: 2865

myDrawable.xml

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

main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/myview"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:background="@drawable/myDrawable">
        <!-- other views in layout-->
    </LinearLayout>

Or add this attribute to you listview

android:listSelector="@android:color/darker_gray"

Upvotes: 0

Pankaj Singh
Pankaj Singh

Reputation: 2311

Save position of clicked item and check it from getView()'s position of adapter. if both are same then set any background color or resources as

   convertView.setBackgroundColor(Color.WHITE);
      or    
   convertView.setBackgroundResource(R.drawable.bg);

where convertView is your inflated layout of adapter.

Upvotes: 5

Related Questions