我在这里找到了一个初学者友好的教程:http://androidrox.wordpress.com/2011/05/13/android-sample-app-drag-and-drop-image-using-touch/
这是我的案例中的xml代码:
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/absLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Countries" />
</AbsoluteLayout>
MainActivity.java:
public class MainActivity extends Activity {
AbsoluteLayout absLayout;
Button myButton = null;
boolean touched = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
absLayout = (AbsoluteLayout) findViewById(R.id.absLayout);
myButton = (Button) findViewById(R.id.myButton);
myButton.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
touched = true;
return false;
}
});
absLayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(touched == true) // any event from down and move
{
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,(int)event.getX()-button_Countries.getWidth()/2,(int)event.getY()-myButton.getHeight()/2);
myButton.setLayoutParams(lp);
}
if(event.getAction()==MotionEvent.ACTION_UP){
touched = false;
}
return true;
}
});
}
基本上,这里发生的事情我需要先触摸myButton一次,将触摸过的布尔值转换为true。然后,我可以通过开始触摸absLayout上的任何位置来拖动myButton。如何在不需要先触摸按钮的情况下简单地拖动按钮?
我尝试在myButton触摸监听器上设置LayoutParams。它会导致拖动进度闪烁。
此外,AbsoluteLayout总是被标记为不推荐使用。"弃用"是什么意思?它是否意味着过时,因此无法使用?或者可用,但可能有更好的解决方案?
myButton.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
touched = true;
return false;
}
});
以上部分负责触摸,使您的按钮能够被拖动。现在删除这部分代码并将声明更改为boolean touched = true;
现在,您应该能够在不首先触摸按钮的情况下进行拖动。