Skip to content Skip to sidebar Skip to footer

How To Keep X And Y Within Layout's View ?

I have a FrameLayout which has a thumb image which the user can drag around. The thumb width is 10dp and height is 10dp. f = (FrameLayout) findViewById(R.id.fl); f.setOnTou

Solution 1:

Have you tried the code from https://stackoverflow.com/a/9112808/663370?

You're letting the image go out of the boundary and then trying to correct for that. Simply don't let it go outside the boundary in the first place. Check the coordinates are valid before processing the event, otherwise just break.

f = (FrameLayout) findViewById(R.id.fl);
f.setOnTouchListener(flt);

f.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
width = f.getMeasuredWidth();
height = f.getMeasuredHeight();

@Override
public boolean onTouch(View v, MotionEvent event) {

    float x = event.getX();
    float y = event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            // Write your code to perform an action on downbreak;
        case MotionEvent.ACTION_MOVE:
            if ( (x <= 0 || x >= width) || (y <= 0 || y >= height) )
                break;
            iv.setX(x);
            iv.setY(y);
            break;
        case MotionEvent.ACTION_UP:
            // Write your code to perform an action on touch upbreak;
    }
    // TODO Auto-generated method stubreturntrue;
}

Post a Comment for "How To Keep X And Y Within Layout's View ?"