Android 拖动控件方法(利用onTouch事件,动态调整控件位置)

拖动控件原理其实很简单,重写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;

	@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
另一种方法:


int[] temp = new int[] { 0, 0 };
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub

		int eventaction = event.getAction();

		int x = (int) event.getRawX();
		int y = (int) event.getRawY();
		int p = (int) event.getX();
		int q = (int) event.getY();


		switch (eventaction) {

		case MotionEvent.ACTION_DOWN: 
			temp[0] = (int) event.getX();
			temp[1] = y - v.getTop();
			break;
		case MotionEvent.ACTION_MOVE: 
			int l = x - temp[0];
			int t = y - temp[1];
			int r = x + v.getWidth() - temp[0];
			int b = y - temp[1] + v.getHeight();
			
			v.layout(l, t, r,b);
			v.postInvalidate();
			break;

		case MotionEvent.ACTION_UP:

			break;
		}

		return false;
	}

© 2011 – 2013, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记