0

我正在使用此代码来移动按钮。正在发生移动,但开始移动时按钮会向下滑动一点。触摸时我也在更改按钮的颜色。

public boolean onTouch(View view, MotionEvent event) {
        float currX,currY;
        int action = event.getAction();

        Button gvup = (Button)findViewById(R.id.giveup);
        gvup.setBackground(getResources().getDrawable(R.drawable.btn));

        switch (action ) {
            case MotionEvent.ACTION_DOWN: {
                startClickTime = Calendar.getInstance().getTimeInMillis();
                mPrevX = event.getX();
                mPrevY = event.getY();
                gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
                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);
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
                view.setLayoutParams(layoutParams);
                gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
                break;
            }
            case MotionEvent.ACTION_CANCEL:
                gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
                break;
            case MotionEvent.ACTION_UP:
                long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
                if(clickDuration < MAX_CLICK_DURATION) {
                    //click event has occurred
                    gvup.setBackground(getResources().getDrawable(R.drawable.btn));
                    giveUp();
                }
                break;
        }
        return true;
    }
}

该代码应该可以完美运行,但无法正常工作。如果代替

mPrevY = event.getY();

我打字

mPrevY = event.getY() + 65;

移动位置适用于许多移动设备,但不是全部,也不适用于标签。

谢谢。

4

1 回答 1

0

尝试在你的 ACTION_DOWN 中使用event.getRawY() , event.getRawX()而不是。event.getY() , event.getX()

于 2016-03-18T21:16:58.500 回答