简体   繁体   中英

onTouchListener: Convert View to ImageView

I have a ArrayList of ImageView's in my Activity-Class and all of them should have the same behavior: As soon as you touch them and move your finger to the right or the left, the x-coordinate of this ImageView should also move.

public boolean onTouch(View v, MotionEvent e) {
    float origin_x = 0;
    float origin_x2 = 0;
    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) v.getLayoutParams();
    switch (e.getActionMasked()) {
        case MotionEvent.ACTION_DOWN: {
            origin_x = e.getX();
            origin_x2 = lp.leftMargin;
            break;
        }
        case MotionEvent.ACTION_MOVE: {
            float diff = e.getX()-origin_x;
            System.out.println(diff);

            lp.setMargins((int) (origin_x2+diff), lp.topMargin, 0, 0);
            v.setLayoutParams(lp);
            break;
        }
    }
    return true;
}

But since I can only use the "View"-Object in the ontouch-Method, I have no possibility to find out which ImageView was touched.

Do you know how I should solve this problem?

Okay, this question has been asked by me very long time ago - but since it received much clicks and even an upvote recently, I decided to answer it now.

If you want to move a View (regardless whether it's an ImageView or any other kind of View), you can use the code from my question post. Setting the margins to the onTouch MotionEvent values will work in RelativeLayouts .


However, my question also included how to find the View Object from the onTouch -Event in an ArrayList of ImageViews .
The answer to that is very simple as well:

ArrayList<ImageView> arrList = new ArrayList<ImageView>();
/** ... **/
int keyOfView = arrList.indexOf(v);

It doesn't matter if v is a View object or an ImageView object. There is no need to cast from View to ImageView for the ArrayList lookup, because the reference will stay that same - and that is what's actually being searched in the List: The reference.


However, if you (for whatever reason) do need an ImageView from a View object and are not sure if all Views are actually ImageView objects, then you can do something like this:

if (v instanceof ImageView) {
     ImageView i = (ImageView) v;
}

This way you will not get cast-errors .

假设您只使用ImageView的触摸侦听器,您可以执行以下操作:

ImageView imageView = (ImageView) v;

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