The best thing to do I think is declare a View that will be your touch area. Here I put all the screen, I put the event on the Layout that match_parent so it's all the screen:
@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>