-1

I want that when I click first time on this check box it should change the image from my Image View and when I click again on same checkbox it should change the image in Image View with another Image.

I Tried:-

checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
         if(isChecked){
             myImage.setBackgroundResource(R.drawable.saveimage);
         }else{
             myImage.setBackgroundResource(R.drawable.deleteimage);
         }
     }
 });
Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
Amit Sharma
  • 261
  • 1
  • 4
  • 20

3 Answers3

1

It's done:-

Take globally (boolean switchStatus = false);

if(switchStatus == true){
    dialog.dismiss();
    image1.setImageResource(R.drawable.icon_delete);
    switchStatus = false;
}else{
    dialog.dismiss();
    image1.setImageResource(R.drawable.icon_checkmark);
    switchStatus = true;
}
Amit Sharma
  • 261
  • 1
  • 4
  • 20
  • This code can be simplified. Use `if (switchStatus) {`, and after the end of the `if/else` statement use `switchStatus = !switchStatus` to flip its value instead of manually setting to `true` or `false`. Would you like me to edit your answer with this simplification? – Michael Dodd Sep 27 '18 at 12:34
  • (Truth be told this can also be reduced to just 3 lines of code using a [ternary operator](https://en.wikipedia.org/wiki/Ternary_operation), but that might be a bit too advanced for the scope of this question) – Michael Dodd Sep 27 '18 at 12:38
0

There is nothing wrong with your code apart from the lack of using setchecked method. When you check your chechbox , call checkbox.setchecked(true) and when you unckeck it, call checkbox.setchecked(false);

0

Because your image is in Drawable I think you should try this:

checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
         if(isChecked){
             myImage.setImageDrawable(getResources().getDrawable(R.drawable.saveimage,getApplicationContext().getTheme()));
         }else{
             myImage.setImageDrawable(getResources().getDrawable((R.drawable.deleteimage,getApplicationContext().getTheme()));
         }
     }
 });
Alex Bean
  • 493
  • 7
  • 19