Android Touch在一段时间内有条件循环?

时间:2014-03-19 17:10:26

标签: java android

好吧,让我说我一次在屏幕上有40个imageViews,我想查看是否有任何一个被触摸,有没有办法压缩我的代码并写一个循环为我做这个?现在我的代码看起来像下面只是更长的因为我有一个巨大的条件为每个imageview。它使代码无穷无尽。每个条件的唯一不同之处是索引值。

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

1 个答案:

答案 0 :(得分:0)

试试这个。

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