2016-03-02 90 views
0

我已经使用在触摸方法使按钮按照我的触摸。 我的代码是按钮不是按照我的触摸

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

我不寒而栗按钮,当我拖它和我的出发点是按钮内。 但是,当起点位于按钮以外的位置时,它不这样做。

回答

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> 
+0

但还是如果我们按一下按钮,开始拖动,其行为不端。不是吗? – Aman

+0

我引导了我的答案。 getRawX()将根据设备获取x和y;)。 – king

+0

唯一的问题是它添加了操作栏和通知栏高度,因此您必须找到一种方法来获取它们并减少它们。就像获取屏幕的高度和根视图的高度一样;) – king