Is there a way to specify an alternative background image/color for a Button in the XML file that is going to be applied onClick
, or do I have to do a But
public void methodOnClick(View view){
Button.setBackgroundResource(R.drawable.nameImage);
}
i recommend use button inside LinearLayout for adjust to size of Linear.
Try:
public void onclick(View v){
ImageView activity= (ImageView) findViewById(R.id.imageview1);
button1.setImageResource(R.drawable.buttonpressed);}
To change image by using code
public void onClick(View v) {
if(v == ButtonName) {
ButtonName.setImageResource(R.drawable.ImageName);
}
}
Or, using an XML file:
<?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/login_selected" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
<item android:drawable="@drawable/login" /> <!-- default -->
</selector>
In OnClick
, just add this code:
ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName));
I used this to change the background for my button
button.setBackground(getResources().getDrawable(R.drawable.primary_button));
"button" is the variable holding my Button, and the image am setting in the background is primary_button
In the latest version of the SDK, you would use the setBackgroundResource
method.
public void onClick(View v) {
if(v == ButtonName) {
ButtonName.setBackgroundResource(R.drawable.ImageResource);
}
}