I want to change the background image of a button when clicked or focused.
This is my code:
Button tiny = (Button)findViewById(R.id.tiny); tiny.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Button tiny = (Button)findViewById(R.id.tiny); tiny.setBackgroundResource(R.drawable.a9p_09_11_00754); TextView txt = (TextView)findViewById(R.id.txt); txt.setText("!---- On click ----!"); } });
Is this code right? Does it calls a button on its event?
In the latest android version, the background image doesn't remove even when you set android:background="@null" . Setting android:minHeight="0dp" works for me.
you can implement in a xml file for this as follows:
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:drawable="@drawable/your_imagename_while_focused"/> <item android:state_pressed="true" android:drawable="@drawable/your_imagename_while_pressed" /> <item android:drawable="@drawable/image_name_while_notpressed" /> //means normal </selector>
now save this xml file in drawable folder and name it suppos abc.xml and set it as follows
Button tiny = (Button)findViewById(R.id.tiny); tiny.setBackgroundResource(R.drawable.abc);
Hope it will help you. :)
Its very easy to implement . For that you need to create a one xml file(selector file) and put it in drawable folder in res. After that set xml file in button's background in your layout file.
<?xml version="1.0" encoding="UTF-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/your_hover_image" /> <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/your_hover_image" /> <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/your_hover_image"/> <item android:drawable="@drawable/your_simple_image" /> </selector>
Now set the above file in button's background.
<Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="@color/grey_text" android:background="@drawable/button_background_selector"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With