拖動控制項原理其實很簡單,重寫activity的onTouchEvent方法,根據手指所在位置得到x,y座標,再用AbsoluteLayout把指定的控制項設定到該位置。
首先,必須用AbsoluteLayout絕對布局:
<?xml version="1.0" encoding="utf-8"?><AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"><TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /></AbsoluteLayout>
JAVA代碼:
package com.pocketdigi.move; import android.app.Activity;import android.os.Bundle;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;import android.widget.TextView;import android.widget.AbsoluteLayout.LayoutParams; @SuppressWarnings("deprecation")public class Main extends Activity {/** Called when the activity is first created. */TextView tv;boolean flag = false; @Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);tv = (TextView) findViewById(R.id.tv);tv.setOnTouchListener(new OnTouchListener() { @Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubflag = true;// 當控制項被點中時,flag設為true//不能寫在onClick事件中return false;} }); } @SuppressWarnings("deprecation")@Overridepublic boolean onTouchEvent(MotionEvent event) {// TODO Auto-generated method stubif (flag) {// flag為true即控制項被點到時,執行行動控制項操作int x = (int) event.getX();int y = (int) event.getY();// 得到X,Y座標LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, x - 10, y - 40);// 四參數分別為寬,高,X,Y座標,wrap_conent為根據內容自動調整// 後面-10,-40是我自己多次調試的結果,因為我發現如果不減,那個座標並不是在指頭下,而是在指頭的右下角// 暫時不知道什麼原因tv.setLayoutParams(params);// 設定最終位置 }if (event.getAction() == MotionEvent.ACTION_UP) {// 手指離開螢幕時,把flag設為falseflag = false;} return super.onTouchEvent(event); }
如果螢幕上有多個控制項需要移動,可以加個int,用於儲存控制項的ID
轉載自:http://www.pocketdigi.com/20110521/293.html