Android可拖拽的ImageButton

所有的View都可以实现onTouchListener,我们可以监听此方法去获取控件的坐标,然后重绘控件的位置。

拖拽的ImageButton

import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.Toast;

public class DraftButtonActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		DisplayMetrics dm = getResources().getDisplayMetrics();
		final int screenWidth = dm.widthPixels;
		final int screenHeight = dm.heightPixels - 50;
		final ImageButton btn = (ImageButton) findViewById(R.id.btn);
		btn.setOnTouchListener(new OnTouchListener() {
			int lastX, lastY;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				int ea = event.getAction();
				Log.i("TAG", "Touch:" + ea);
				switch (ea) {
				case MotionEvent.ACTION_DOWN:
					lastX = (int) event.getRawX();// 获取触摸事件触摸位置的原始X坐标
					lastY = (int) event.getRawY();
					break;
				case MotionEvent.ACTION_MOVE:
					int dx = (int) event.getRawX() - lastX;
					int dy = (int) event.getRawY() - lastY;
					int l = v.getLeft() + dx;
					int b = v.getBottom() + dy;
					int r = v.getRight() + dx;
					int t = v.getTop() + dy;
					// 下面判断移动是否超出屏幕
					if (l < 0)="" {="" l="0;" r="l" +="" v.getwidth();="" }="" if="" (t="">< 0)="" {="" t="0;" b="t" +="" v.getheight();="" }="" if="" (r=""> screenWidth) {
						r = screenWidth;
						l = r - v.getWidth();
					}
					if (b > screenHeight) {
						b = screenHeight;
						t = b - v.getHeight();
					}
					v.layout(l, t, r, b);
					lastX = (int) event.getRawX();
					lastY = (int) event.getRawY();
					Toast.makeText(DraftButtonActivity.this,
							"当前位置:" + l + "," + t + "," + r + "," + b,
							Toast.LENGTH_SHORT).show();
					v.postInvalidate();
					break;
				case MotionEvent.ACTION_UP:
					break;
				}
				return false;
			}
		});
	}
}
暂无评论
  • 1:请一针见血的评论。
  • 2:评论需要审核通过后才能显示。
  • 3:评论字数限制在1000字以内。
  • 当前字数:0
热门文章
推荐文章
随机文章
关于本站 - 广告服务 - 版权声明 - 联系我们 - 友情链接 - 网站地图 - 帮助中心