Android Touch conditional within a while loop?

Okay let's say I have 40 imageViews on the screen at once and I want to check to see if any of them are being touched, is there any way to condense my code and write a loop to do it for me? Right now my code looks like what is below only much longer because I have a giant conditional for each imageview. It makes for endless and gross looking code. The only thing different about each conditional is the index value.

public boolean onTouch(View v, MotionEvent event) 
{
    switch (event.getAction())
    {

        case MotionEvent.ACTION_MOVE:

            float x = event.getRawX();
            float y = event.getRawY();


                 if (x > imageViewArray[0].getX() && x < imageViewArray[0].getX() + imageViewArray[0].getWidth() && y > imageViewArray[0].getY() && y < imageViewArray[0].getY() + imageViewArray[0].getHeight()) {

                    System.out.println("imageView0 was touched");
                 }
                 if (x > imageViewArray[1].getX() && x < imageViewArray[1].getX() + imageViewArray[1].getWidth() && y > imageViewArray[1].getY() && y < imageViewArray[1].getY() + imageViewArray[1].getHeight()) {

                    System.out.println("imageView1 was touched");

                 }
                 if (x > imageViewArray[2].getX() && x < imageViewArray[2].getX() + imageViewArray[2].getWidth() && y > imageViewArray[2].getY() && y < imageViewArray[2].getY() + imageViewArray[2].getHeight()) {

                    System.out.println("imageView2 was touched");

                }

            break;
    }
    return true;
}

Answers


Try this.

    ArrayList<ImageView> myImageViewsList = new ArrayList<ImageView>();
    ...
    //Add ImageView's to list
    ...
    public boolean onTouch(View v, MotionEvent event) 
    {
        ImageView touchedView;

        for(ImageView view : myImageViewsList) {
            Rect rect;
            view.getDrawingRect(rect);
            if(rect.contains((int)event.getX(),(int)event.getY())) {
                touchedView = view; // that is a touched ImageView
                break;
            }
        }
        return true;
    }

Need Your Help

How to effectively validate Asp.Net membership forms

asp.net-membership validation

What are other suggestions and sample code for efficiently validating the Register and/or login page. Perhaps use of jQuery?

How to check if a specified key exists in a given S3 bucket using Java

java amazon-web-services amazon-s3 aws-sdk

I would like to check if a key exists in a given bucket using Java. I looked at the API but there aren't any methods that are useful. I tried to use getObject but it threw an exception.