简体   繁体   中英

Android - how to drag a view within screen size?

i am working on drag and drop functionality. Works good , but a button can be dragged outside of screen width,height. I want to drag only inside 1080*1920 screen size. Pls suggest me.

i am doing this :

onCreate
{
Button btn_tag=new Button(getApplicationContext);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    250,100);



            lp.leftMargin = (int) event.getX();

            lp.topMargin = (int) event.getY();// TOP MARGIN;

            rl_main.addView(btn_tag, lp);
}

// Touch Event


final int X = (int) event.getRawX();
        final int Y = (int) event.getRawY();
case MotionEvent.ACTION_DOWN:

            RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) v
            .getLayoutParams();

            _xDelta = X - lParams.leftMargin;
            _yDelta = Y - lParams.topMargin;

            break;

case MotionEvent.ACTION_MOVE:

RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v
                    .getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
                layoutParams.topMargin = Y - _yDelta;
v.setLayoutParams(layoutParams);

You can use an if statement to check if the button is out of bounds of the screen when you are trying to move it.

sample:

if((X - xDelta) > 0 && (X - xDelta) < 1080 )
  layoutParams.leftMargin = X - _xDelta;
if((Y - xDelta) > 0 && (Y - xDelta) < 1920)
  layoutParams.topMargin = Y - _yDelta;

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