I have a button
Button button = (Button)findViewById(R.id.button);
button.setBakgroundResource(R.drawable.icon);
If I want to check which background resource button has, is it possible to do so? how.
For example :
if (button.getResourceId()==R.drawable.icon)
do something with code...
UPDATE: THE CONDITION IS FALSE I WANT IT TO BE TRUE THE IMAGES DO NOT MATCH
vi.findViewById(R.id.button1).setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
v.findViewById(R.id.button1).setBackgroundResource(R.drawable.boutton_off);
Drawable aImg = (Drawable)v.findViewById(R.id.button1).getBackground();
Drawable bImg = v.getResources().getDrawable(R.drawable.boutton_off);
if(aImg==bImg){
System.out.println("On");
}else
System.out.println("off");
//main.popMessage(position);
}
});
If you are setting multiple drawable backgrounds for a button then you check it as follows
if(button.getBackground().getConstantState()==getResources().getDrawable(R.drawable.name1).getConstantState())
{
//Your code
}
else if(button.getBackground().getConstantState()==getResources().getDrawable(R.drawable.name2).getConstantState())
{
//Your code
}
else
{
//Your code
}
You can use button.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.name1).getConstantState())
if above code doesn't work
It seems not to be possible. The ressource is resolved to a Drawable and thats all you can get back in the standard functionality. Maybe there is a way to resolve the drawable back to the id in another way, but this functionality is not impleneted in the buttonclass.
If you need an easy access to that resourceId and you are setting the ressource from code you can write your ButtonClass implementing the Android Button and overload/create the setBackgroundResource to save the id in an additional field you can then access. This, of course, doesn't work, if the button gets his BackgroundRessource not due a function call from your side.
Here some code.
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
public class MyButton extends Button {
private int bgId;
public MyButton(Context context) {
super(context);
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setBackgroundResource(int resId) {
super.setBackgroundResource(resId);
bgId = resId;
}
public int getBackgroundId() {
return bgId;
}
}
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