Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change background image of button when clicked/focused?

Tags:

android

button

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?

like image 206
Omid Nazifi Avatar asked Oct 18 '11 06:10

Omid Nazifi


People also ask

How do I remove background from Imagebutton?

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.


2 Answers

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. :)

like image 160
Android Killer Avatar answered Oct 07 '22 01:10

Android Killer


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.

button_background_selector.xml

<?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"/> 
like image 29
Chirag Avatar answered Oct 07 '22 01:10

Chirag