Android拖动控件

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

转载自:http://www.pocketdigi.com/20110521/293.html


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值