I have two buttons in android. Btn1 and Btn2. I need to show Btn1 by default and when is is clicked I need to show Btn2 in place of Btn1. Again when Btn2 is clicked, it should be replaced with Btn2. Please help me with some example..
My Code:
btn1 = (ImageView) findViewById(R.id.firstbtn);
btn2 = (ImageView) findViewById(R.id.secondbutton);
btn2.setVisibility(ImageView.GONE);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btn2.setVisibility(ImageView.VISIBLE);
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btn2.setVisibility(ImageView.GONE);
}
});
Thanks in advance
You can use same button and change its label alternatively and as per level you can put the check and perform appropriate work.
As per your updated code get to know your are using ImageView so try this
ImageView btn = (ImageView) findViewById(R.id.secondbutton);
btn.setTag("1");//can use one empty String "" and null instead of "1" and "2" for optimization
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Object obj = v.getTag();
if(obj instanceof String){
if("1".equals(obj)){
v.setTag("2");
//Your first button state
}else if("2".equals(obj)){
v.setTag("1");
//Your second button state
}
}
...
If your case is specific for two buttons then you can use two String compare operations
ImageView btn = (ImageView) findViewById(R.id.secondbutton);
btn.setTag(null);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(v.getTag() instanceof String){
v.setTag(null);
//Your first button state
} else {
v.setTag("");
//Your second button state
}
If you want to make your code work right
btn1 = (ImageView) findViewById(R.id.firstbtn);
btn2 = (ImageView) findViewById(R.id.secondbutton);
btn2.setVisibility(ImageView.GONE);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.setVisibility(ImageView.GONE);
btn2.setVisibility(ImageView.VISIBLE);
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.setVisibility(ImageView.GONE);
btn1.setVisibility(ImageView.VISIBLE);
}
});
change this
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btn2.setVisibility(ImageView.GONE);
}
});
by
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btn2.setVisibility(View.GONE);
btn1.setVisibility(View.VISIBLE);
}
});
and this
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btn2.setVisibility(View.VISIBLE);
}
});
by
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btn1.setVisibility(View.GONE);
btn2.setVisibility(View.VISIBLE);
}
});
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