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?
To change the button background we can follow 2 methods
In the button OnClick, just add this code:
2.Create button_background.xml in the drawable folder.(using xml)
res -> drawable -> button_background.xml
Now set the above file in button's background file.
2nd method is better for setting the background fd button
You just need to set background and give previous.xml file in background of button in your layout file.
and done.Edit Following is previous.xml file in drawable directory
You can also create shapes directly inside the
item
tag, in case you want to add some more details to your view, like this:Beware that Android will cycle through the items from top to bottom, therefore, you must place the
item
without condition on the bottom of the list (so it acts like a default/fallback).Sorry this is wrong.
For changing background color/image based on the particular event(focus, press, normal), you need to define a button selector file and implement it as background for button.
For example: button_selector.xml (define this file inside the drawable folder)
And apply it as:
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
Now set the above file in button's background.
use this code create xml file in drawable folder name:button
and in button xml file