如何限制拖放ImageView Android的区域

时间:2016-01-05 22:36:38

标签: android android-layout drag-and-drop

如何限制移动ImageView的区域,使其不会超出RelativeLayout区域。

我移动ImageView的代码是:

public boolean onTouch(View v, MotionEvent me) {
    if (me.getAction() == MotionEvent.ACTION_DOWN) {
        oldXvalue = me.getX();
        oldYvalue = me.getY();

    } else if (me.getAction() == MotionEvent.ACTION_MOVE) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(v.getWidth(), v.getHeight());
        params.leftMargin = (int) (me.getRawX() - (v.getWidth() / 2));
        params.topMargin = (int) (me.getRawY() - (v.getHeight()));
        v.setLayoutParams(params);

    }
    return true;
}

我一直在寻找StackOverflow上的答案,但没找到它。

1 个答案:

答案 0 :(得分:0)

        if(params.leftMargin<=0){
            params.leftMargin=0;
        }
        if(params.topMargin<=0){
            params.topMargin=0;
        }

        if(params.leftMargin>=width-(v.getWidth())){
            params.leftMargin=(int)width-(v.getWidth());
        }

        if(params.topMargin>height-(v.getHeight())){
            params.topMargin=(int)height-(v.getHeight());
        }


        v.setLayoutParams(params);

解决了! :)