拖动控件原理其实很简单,重写activity的onTouchEvent方法,根据手指所在位置得到x,y座标,再用AbsoluteLayout把指定的控件设置到该位置。
JAVA代码:
首先,必须用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;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv);
tv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
flag = true;
// 当控件被点中时,flag设为true
//不能写在onClick事件中
return false;
}
});
}
@SuppressWarnings("deprecation")
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if (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设为false
flag = false;
}
return super.onTouchEvent(event);
}
如果屏幕上有多个控件需要移动,可以加个int,用于存储控件的ID