skip to Main Content

If I want to change a image to another by the click of a button and then back to the previous image again by the click of the same button on imageview in android studio how to do that in short and easiest way? As I am new to it I am not familiar with all the functions of imageview.

For example:-
I wrote this code to do what I needed after a lot of failure in finding a easier way.

int i=0;
public void change(View v){

    int img[] = {R.drawable.cat1,R.drawable.cat2};
    ImageView cat = findViewById(R.id.imageView2);
    if(i==0)
    {cat.setImageResource(img[1]);
    i=1;}
    else {cat.setImageResource(img[0]);
    i=0;}
 }

Before I was trying to do something like this:-

public void change(View v){

    ImageView cat = findViewById(R.id.imageView2);
    if(cat.getDrawable()==R.drawable.cat2;)
    {cat.setImageResource(R.drawable.cat1);}
 else
    {cat.setImageResource(R.drawable.cat1};
}

But it kept giving error that they have different type and I also tried some other functions named getId() but it didnt work either…
So my main objective is, is there a function through which I can campare the resource of image view directly with the image in drawable folder and how to implement it in if else or some other conditional statement?

2

Answers


  1. The first approach should work, but the i value seems not tightly coupled to the ImageView. So, instead you can set a tag to the ImageView that equals to the current drawable id:

    Initial tag:

    ImageView cat = findViewById(R.id.imageView2);
    cat.setImageResource(R.drawable.cat1);
    cat.setTag(R.drawable.cat1);
    

    And click listener callback:

    public void change(View v){
    
        ImageView cat = findViewById(R.id.imageView2);
        int tag = (int) cat.getTag();
        
        if(tag == R.drawable.cat2){
            cat.setImageResource(R.drawable.cat1);
            cat.setTag(R.drawable.cat1);
            
        } else {
            cat.setImageResource(R.drawable.cat2);
            cat.setTag(R.drawable.cat2);
        }
        
    }
    
    Login or Signup to reply.
  2. You could try StateListDrawable, LevelListDrawable, with each state/level, it will change image depend on your state/level

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search