Spike
Spike

Reputation: 147

Changing background color through styles

I have an image button and I want to change the color of a button when pressed. First I show it with a transparent as a default state color as below. But it doesn't show highlighted when pressed. So I decided to use other color to highlight when pressed using state drawable. But how to keep background color through styles wise. Means by default it should be transparent and when pressed it has to show other color.

present code:

<ImageButton 
        android:id="@+id/imgbutton"
            android:layout_width="20dp"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:src="@drawable/ic_launcher"
            android:background="@android:color/transparent"
        />

Need to be coded:

<ImageButton 
        android:id="@+id/imgbutton"
            android:layout_width="20dp"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:src="@drawable/ic_launcher"
            android:background="@drawable/btnselector"
        />

So what should be the btnselector.xml here?

Upvotes: 1

Views: 268

Answers (1)

Blackbelt
Blackbelt

Reputation: 157457

put it inside res/color

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

<item android:state_pressed="true" android:color="@color/green_text_color"/> <!-- pressed -->
<item android:state_focused="true" android:color="@color/green_text_color"/> <!-- focused -->
<item android:color="@android:color/white"/> <!-- default -->

</selector>

create a new shape, inside res/drawable

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
       android:shape="rectangle"> 
     <solid android:color="@color/yourxmlfile" /> 
</shape>

and put it as background

or a res/drawable selector

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
      <item android:drawable="@drawable/green_botton_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/green_botton_highlited"
          android:state_focused="true" />
    <item android:drawable="@drawable/green_botton" />

</selector>

Upvotes: 1

Related Questions