按钮不是我的触摸

时间:2016-03-02 00:16:46

标签: android ontouchevent

我使用触摸方法按下我的触摸按钮。 我的代码是

b.setX(event.getX());
b.setY(event.getY());

当我拖动它时我的按钮颤抖,我的起点在按钮内。 但是当起点不在按钮的某个位置时,它就不会这样做。

1 个答案:

答案 0 :(得分:0)

我认为最好的办法是声明一个将成为您触摸区域的视图。在这里我放了所有的屏幕,我把事件放在了match_parent的布局上,所以它就是所有的屏幕:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    final Button btn = (Button)findViewById(R.id.second);

    final RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout);

    layout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            btn.setX(event.getX());
            btn.setY(event.getY());
            return true;
        }
    });
btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int[] pos = new int[2];
            layout.getLocationOnScreen(pos);

            btn.setX(event.getRawX());
            btn.setY(event.getRawY() - pos[1]);
            return true;
        }
    });
}

的xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
android:id="@+id/layout">

<Button
    android:text="OK"
    android:id="@+id/second"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/holo_red_dark" />


</RelativeLayout>
相关问题