android 图片拖动简单例子

package com.xf;
import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class XFActivity extends Activity implements OnTouchListener{

	private ImageView iv;//拖动用的图片
	int x,y;//图片上一个的XY位置
	int screenWidth,screenHeight;//当前屏幕的宽度和高度(像素表示)
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        DisplayMetrics dm = getResources().getDisplayMetrics(); 
        screenWidth = dm.widthPixels; 
        screenHeight = dm.heightPixels; 
        
        iv=(ImageView)findViewById(R.id.im);
        iv.setOnTouchListener(this);
    }
	@Override
	public boolean onTouch(View v, MotionEvent e) {
		System.out.println(e.getAction());
		switch(e.getAction()){
			case MotionEvent.ACTION_DOWN://按下
				//获取按下时的X,Y轴位置  
				x = (int) e.getRawX();
	            y = (int) e.getRawY();
				break;
			case MotionEvent.ACTION_UP://松开
				
				break;
			case MotionEvent.ACTION_MOVE://执行 ACTION_DOWN 才执行 ACTION_MOVE
				
				int mX = (int)e.getRawX()-x;
				int mY = (int)e.getRawY()-y;
				
				int left = v.getLeft()+mX;
				int top = v.getTop()+mY;
				int right = v.getRight()+mX;
				int bottom = v.getBottom()+mY;
				
				  // 设置不能出界 
                if (left < 0) { 
                    left = 0; 
                    right = left + v.getWidth(); 
                } 
 
                if (right > screenWidth) { 
                    right = screenWidth; 
                    left = right - v.getWidth(); 
                } 
 
                if (top < 0) { 
                    top = 0; 
                    bottom = top + v.getHeight(); 
                } 
 
                if (bottom > screenHeight) { 
                    bottom = screenHeight; 
                    top = bottom - v.getHeight(); 
                }
								
				v.layout(left,top,right,bottom);
				
				//记住手指滑动所在的X,Y轴位置,也就是上一个X,Y轴的位置
				x = (int) e.getRawX();  
                y = (int) e.getRawY(); 
				break;
		}
		return true;
	}
	
	
}

你可能感兴趣的:(android 图片拖动简单例子)