Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android button background selector

I want to use the following selector for button:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/jobs" android:state_pressed="true">
        <shape android:shape="rectangle">
            <corners android:radius="5dp" />
        </shape>
<scale android:scaleHeight="90%" android:scaleWidth="90%" />
    </item>
    <item android:drawable="@drawable/jobs"></item>

</selector>

But it does not work. I want to make buttons corners round and 10% small in size with the same drawable. Actually I want to give a button pressed effect using single drawable. Is it possible?

like image 940
Khawar Raza Avatar asked Aug 08 '12 14:08

Khawar Raza


People also ask

How can change button background drawable programmatically in Android?

How to set Background of button in Android programmatically? setBackgroundResource() method is used to change the button background programmatically. setBackgroundResource(int id) accepts id of drawable resource and applies the background to the button.


1 Answers

I find it best to separate the state logic and drawable code. From the Android docs: http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

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

I would then put the code to give rounded corners in a separate drawable XML. I'm not sure if you can even do such things directly in a selector.

like image 153
telkins Avatar answered Sep 28 '22 20:09

telkins