Tr. Buu
Tr. Buu

Reputation: 89

How to handle touch event on a ImageView

I have three Images. When I first touch, first Image is shown, when I second touch, second Image is shown, and then when I third touch, third Image is shown. After all, when I fourth touch, I want to show first Image return and so on.

Can someone point me to show how handling or touching on a ImageView of android?

Upvotes: 0

Views: 915

Answers (2)

LionHere
LionHere

Reputation: 9

how to handle click on an ImageView

You can simply set a View.OnClickListener for your ImageView:

imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // do stuff
        }
    });

Upvotes: 0

Phil3992
Phil3992

Reputation: 1055

The below should do what you need:

public class MainActivity extends Activity {
ImageView image;
int i=1;
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        image = (ImageView) findViewById(R.id.imageViewName);      
        setButtonOnClickListeners();       
            }
        }
        image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                if (i==1){
                image.setImageResource(R.drawable.image1);
                i++;
                }
                else if(i==2){
                    image.setImageResource(R.drawable.image2);
                    i++;
                }
                else if(i==3){
                    image.setImageResource(R.drawable.image3);
                    i++;
                }
                else if(i==4){
                    image.setImageResource(R.drawable.image4);
                    i=1;
                }
        }
    });

I've not tested but the idea is correct. When you click the image it will change the drawable depending on the value of i. When you get image 1 i will equal 1. Onclick will increment i until i==4 which it will reset to 1 as you requested.

A while loop might be tidier but this was the quickest soultion I thought of.

Upvotes: 1

Related Questions