0

I have used On touch method to make a button follow my touch. My code is

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

My button shivers when I drag it and my starting point is inside the button. But it doesn't do so when the starting point is somewhere other than the button.

Aman
  • 23
  • 8

1 Answers1

0

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>
king
  • 507
  • 1
  • 4
  • 17
  • But still if we click the button and start dragging, it misbehaves. Doesn't it? – Aman Mar 02 '16 at 01:36
  • I eddited my answer. getRawX() will get you the x and y based on the device ;). – king Mar 02 '16 at 01:38
  • The only problem is that it's adding the actionbar and the notifiction bar height so you have to find a way to get them and substract. Like getting the height of the screen and the height of the root view for exemple ;) – king Mar 02 '16 at 01:47
  • I already knew that but please tell me the way to get height of the notification bar and Action bar. – Aman Mar 02 '16 at 01:55