android控件拖动

小案例:

    实现一个在屏幕上可以随意拖动的按钮(ps:其他控件的拖动原理是一样)

  实现步骤:

   第一步,写个布局文件:
    
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="拖动试试" />

</LinearLayout>

第二步,在MainActivity上实现控件的拖动逻辑代码:
   
package com.ljgui.draft;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class MainActivity extends Activity {
	private Button btn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn = (Button) findViewById(R.id.btn);
		
		// 获得屏幕宽的像素
		final int creeenwidth = getResources().getDisplayMetrics().widthPixels;
		// 获得屏幕高的像素(减50是因为不让控件被拖出屏幕)
		final int screenheight = getResources().getDisplayMetrics().heightPixels-50;
		
		//给按钮添加触摸事件监听
		btn.setOnTouchListener(new OnTouchListener() {
			int xsrc = 0;
			int ysrc = 0;
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				int action = event.getAction();
				switch (action) {
				case MotionEvent.ACTION_DOWN:
					//获取控件最初位置
					xsrc = (int) event.getRawX();
					ysrc = (int) event.getRawY();
//					System.out.println(xsrc+"-ACTION_DOWN--"+ysrc);
					break;
				case MotionEvent.ACTION_MOVE:
					//获取控件拖动的距离
					int x = (int) (event.getRawX()-xsrc);
					int y = (int) (event.getRawY()-ysrc);
					
//					System.out.println(x+"-ACTION_MOVE--"+y);
					
					//获取控件的坐标并加上被拖动的距离
					int left = v.getLeft() + x;
					int top = v.getTop() +y;
					int right = v.getRight() + x;
					int bottom = v.getBottom() +y;
					
					//处理屏幕边界问题
					if(left<0){
						left=0;
						right=v.getWidth()+left;
					}
					
					if(right>creeenwidth){
						right=creeenwidth;
						left =right- v.getWidth();
					}
					
					if(top<0){
						top=0;
						bottom=v.getHeight()+top;
					}
					if(bottom>screenheight){
						bottom=screenheight;
						top=bottom-v.getHeight();
					}
					
					//设置控件的显示位置
					v.layout(left, top, right, bottom);
					
					xsrc = (int) event.getRawX(); //获取控件的新位置
					ysrc = (int) event.getRawY();
					
//					System.out.println(xsrc+"----"+ysrc);
					break;
				case MotionEvent.ACTION_UP:
					
					break;
				}
				return false;
			}
		});
	}
}

代码中有注释,不明白的地方建议自己去进行测试,这其实也是一个很好的自学方法,先猜测结果然后去测试验证自己的猜想是不是正确的。这样会让你印象比较深刻。


     

猜你喜欢

转载自blog.csdn.net/lujiangui/article/details/38926103