[英]Button isn't following my touch
我使用了On touch方法来使按钮跟随我的触摸。 我的代码是
b.setX(event.getX());
b.setY(event.getY());
当我拖动按钮时,其按钮会发抖,并且起点在按钮内部。 但是当起点不在按钮之外时,它不会这样做。
我认为最好的办法是声明一个View,它将成为您的触摸区域。 在这里,我放置了所有屏幕,将事件放置在具有match_parent的Layout上,因此是所有屏幕:
@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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.