In iOS, if I set a button's background to an image, when I press the button, the whole content of the button (including the text) will be shadowed. Can I achieve the same effect in Android, or do I have to use different images for different states? Also, even if I use different images for different states, how do I make the text also shadowed? A dirty way is to set a OnClickListener
to the button and programatically shadow the text when pressed, but are there any other ways?
I´ve been trying to find a solution for this for a while now but couldn´t find anything so I came up with a pretty neat solution which works on all image buttons. Just like iOS.
Create a Black, 10% transparent image and save it as PNG. I call it button_pressed.png. You can use this image, http://img84.imageshack.us/img84/7924/buttonpressed.png
Create a drawable called something relevant, I call it "button_pressed_layout.xml"
<?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" /> </selector>
Now put your button image in the LinearLayout and then the Button inside the LinearLayout. In the Button use button_pressed_layout.xml as background.
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/button_image"> <Button android:id="@+id/myButtonId" android:text="@string/Continue" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/button_pressed_layout" android:textColor="#FFF" android:textSize="16dp" > </Button> </LinearLayout>
That´s it!
To get a pressed-state without creating a 2nd button image, I created an OnTouchListener to change the button's alpha. This is not the most beautiful pressed state, but gives an effective automatic behavior.
public class PressedStateOnTouchListener implements OnTouchListener
{
PressedStateOnTouchListener( float alphaNormal )
{
mAlphaNormal = alphaNormal;
}
public boolean onTouch( View theView, MotionEvent motionEvent )
{
switch( motionEvent.getAction() ) {
case MotionEvent.ACTION_DOWN:
theView.setAlpha( mAlphaNormal / 2.0f );
break;
case MotionEvent.ACTION_UP:
theView.setAlpha( mAlphaNormal );
break;
}
// return false because I still want this to bubble off into an onClick
return false;
}
private float mAlphaNormal;
}
In your Activity, apply this listener to each button:
Button theButton = (Button)findViewById( R.id.my_button_id );
theButton.setOnTouchListener( new PressedStateOnTouchListener( theButton.getAlpha() ));
© 2022 - 2024 — McMap. All rights reserved.