SteBra
SteBra

Reputation: 4247

Pressed button background change in Android as in Xcode

I was wondering is there any way to make your customised ImageButton or a Button change background on click.

Now, I know that it can be done through XML doing something like this:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/login_selected" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
<item android:drawable="@drawable/login" /> <!-- default -->
</selector>

Or in code, doing something like this, onClick:

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setImageResource(R.drawable.ImageName);
   }
}

BUT, If I want to do it this way, that means I have to use 2 different images for one button. One with the normal and one with the pressed state. That can be problem if I have, lets say, 100 different buttons. That's 200 images, just for buttons. You can Imagine resources saving with the ability of just telling eclipse it's a button, and I want it to go a bit darker, when I press it.

So I am asking is there a way of doing it like in Xcode ? Setting up a background or an image of a button and it shades a bit when pressed, not changing the background or anything, just shading it a bit,like this

Upvotes: 1

Views: 359

Answers (2)

Ali Ahmad
Ali Ahmad

Reputation: 1351

Try this code if the name of enter image description here

is btn_back.png

make the following darawble xml file

btn_semi.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">
    <solid
        android:color="#50000011" 
        />
    <corners android:radius="10dip"/>
</shape>

btn_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" >
        <layer-list>
            <item android:drawable="@drawable/btn_back"></item>
            <item android:drawable="@drawable/btn_semi"></item>
        </layer-list>
    </item>
    <item android:drawable="@drawable/btn_back"></item>
</selector>

Create a button in layout

<Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:background="@drawable/btn_background" 
       />

Upvotes: 1

Apoorv
Apoorv

Reputation: 13520

You can try to use setAlpha but its only available in API 11 and above

Upvotes: 0

Related Questions