Home > Blockchain >  How to compare images in Android (java)
How to compare images in Android (java)

Time:01-23

I recently started learning to code with Android Studio. And I wanted a button when clicked to toggle between two images, but I cant seem to compare them.

I tried comparing them but it doesn't think they are the same.

  ImageView dog = new ImageView(this);
  dog.setImageResource(R.drawable.dog);

  ImageView goofy = new ImageView(this);
  goofy.setImageResource(R.drawable.goofydog);

  if(img==dog)
  {
      img.setImageResource(R.drawable.goofydog);
  }
  else{
      img.setImageResource(R.drawable.dog);
  }

CodePudding user response:

You can only compare primitive types (String, Int, Double...) in If statements, if you compare object it will compare the instance of each object which in your case is different.

If you want to toggle between two images based on what your imageView is actually displaying you should compare the Int resources that is displayed like that :

Image img = findViewById(R.id.image_view);
  Button button = findViewById(R.id.button);

  String current = "";

  button.setOnClickListener(new View.OnClickListener( v-> {
       @Override
       void onClick(View v){
           if (img.getDrawable() == ResourcesCompat.getDrawable(getResources(),
            R.drawable.dog, null)) {
        img.setImageResource(R.drawable.goofyDog);
           } else {
             img.setImageResource(R.drawable.dog);
    }
       }
  }));

If you want to learn more about using objects in If statement, you can learn more about instance of object here : https://en.wikipedia.org/wiki/Instance_(computer_science)

CodePudding user response:

You can't compare images the way you are doing. If you want to toggle between two images using a button, you can simple do:

  Image img = findViewById(R.id.image_view);
  Button button = findViewById(R.id.button);

  String current = "";

  button.setOnClickListener(new View.OnClickListener( v-> {
       @Override
       void onClick(View v){
            if (current = "Dog") {
                img.setImageResource(R.drawable.dog);
                current = "Dog";
            } else {
                img.setImageResource(R.drawable.goofydog);
                current = "Goofy";
            }
       }
  }));
  • Related