在屏幕高度和宽度上移动浮动按钮

时间:2016-06-17 12:21:02

标签: android button touch movable

我想在屏幕上移动一个按钮,我试着按照代码

它正在工作但移出屏幕。是否可以限制其在屏幕内的移动。 还尝试获取屏幕高度和宽度,并设置为布局高度和宽度,但没有用。

public class MultiTouchListener implements View.OnTouchListener {

    private float mPrevX;
    private float mPrevY;

    public MainActivity mainActivity;

    public MultiTouchListener(MainActivity mainActivity1) {
        mainActivity = mainActivity1;
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        float currX, currY;
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN: {

                mPrevX = event.getX();
                mPrevY = event.getY();
                break;
            }

            case MotionEvent.ACTION_MOVE: {

                currX = event.getRawX();
                currY = event.getRawY();


                ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
                marginParams.setMargins((int) (currX - mPrevX), (int) (currY - mPrevY), 0, 0);
                CoordinatorLayout.LayoutParams layoutParams = new CoordinatorLayout.LayoutParams(marginParams);
                view.setLayoutParams(layoutParams);


                break;
            }


            case MotionEvent.ACTION_CANCEL:
                break;

            case MotionEvent.ACTION_UP:

                break;
        }
        return true;
    }
}

0 个答案:

没有答案