實現圖片拖動,圖片拖動
要求:
1.通過手指移動來拖動圖片
2.控製圖片不能超出螢幕顯示地區
技術點:
1.MotionEvent處理
2.對View進行動態定位(layout)
activity_main.xml:
<RelativeLayout 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" > <ImageView android:id="@+id/iv_main" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/test"/></RelativeLayout>
MainActivity:
public class MainActivity extends Activity implements OnTouchListener {private ImageView iv_main;private RelativeLayout parentView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);iv_main = (ImageView) findViewById(R.id.iv_main);parentView = (RelativeLayout) iv_main.getParent();/*int right = parentView.getRight(); //0int bottom = parentView.getBottom(); //0Toast.makeText(this, right+"---"+bottom, 1).show();*///設定touch監聽 iv_main.setOnTouchListener(this);}private int lastX;private int lastY;private int maxRight;private int maxBottom;@Overridepublic boolean onTouch(View v, MotionEvent event) {//得到事件的座標int eventX = (int) event.getRawX();int eventY = (int) event.getRawY();switch (event.getAction()) {case MotionEvent.ACTION_DOWN://得到父視圖的right/bottomif(maxRight==0) {//保證只賦一次值maxRight = parentView.getRight();maxBottom = parentView.getBottom();}//第一次記錄lastX/lastYlastX =eventX;lastY = eventY;break;case MotionEvent.ACTION_MOVE://計算事件的位移int dx = eventX-lastX;int dy = eventY-lastY;//根據事件的位移來移動imageViewint left = iv_main.getLeft()+dx;int top = iv_main.getTop()+dy;int right = iv_main.getRight()+dx;int bottom = iv_main.getBottom()+dy;//限制left >=0if(left<0) {right += -left;left = 0;}//限制topif(top<0) {bottom += -top;top = 0;}//限制right <=maxRightif(right>maxRight) {left -= right-maxRight;right = maxRight;}//限制bottom <=maxBottomif(bottom>maxBottom) {top -= bottom-maxBottom;bottom = maxBottom;}iv_main.layout(left, top, right, bottom);//再次記錄lastX/lastYlastX = eventX;lastY = eventY;break;default:break;}return true;//所有的motionEvent都交給imageView處理}}