我找到了一個適合初學者的教程在這裏:http://androidrox.wordpress.com/2011/05/13/android-sample-app-drag-and-drop-image-using-touch/Android - 如何簡單地拖放一個按鈕?
這裏是我的情況下的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 touch listener上設置LayoutParams。它會導致拖動進度閃爍。
此外,AbsoluteLayout始終標記爲已棄用。 「棄用」是指什麼?這是否意味着過時,因此無法使用?或可用,但可能有更好的解決方案?
檢查出類似的問題,我的回答[這裏] [1] [1]:http://stackoverflow.com/questions/20606802/how-to-swipe-a-button-ontouch -event-in-android/20607696#20607696 – GrIsHu