简体   繁体   中英

How to compare images in Android (java)

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);
  }

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)

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";
            }
       }
  }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM