简体   繁体   中英

How can I stop making the button leaves the screen when I move it?

I have a button following my finger position when I touch it but if I put my finger on screen edges, The button will be outside of the screen, How can I check if the button is outside the screen or no because I don't want the button leaves the screen.

@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View view, MotionEvent event) {
    if (view.getId() == R.id.img_view) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            dX = view.getX() - event.getRawX();
            dY = view.getY() - event.getRawY();
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            view.setX(event.getRawX() + dX);
            view.setY(event.getRawY() + dY);
        }
    }
    return true;
}

check out how to measure whole screen

 DisplayMetrics displayMetrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
 int scrHeight = displayMetrics.heightPixels;
 int scrWidth = displayMetrics.widthPixels;

then value set for setX method can't be higher than touch position + width of dragged view, setY can't be higher than touch position + height of dragged view

int xToSet = event.getRawX() + dX;
if (xToSet + draggedView.getMeasuredWidth() > scrWidth) 
    xToSet = scrWidth - draggedView.getMeasuredWidth();
view.setX(xToSet);


int yToSet = event.getRawY() + dY;
if (yToSet + draggedView.getMeasuredHeight() > scrHeight) 
    yToSet = scrHeight - draggedView.getMeasuredHeight();
view.setY(yToSet);

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