這裡示範控制項拖動的動畫:
原理就是響應控制項的Touch事件,在Touch事件中對移動進行處理,注意,一定要在布局檔案中設定控制項的
android:clickable="true"。
代碼如下:
package com.zhycheng.draftdemo;import android.app.Activity;import android.os.Bundle;import android.view.Display;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;import android.widget.ImageView;public class DraftDemoActivity extends Activity implements OnTouchListener {ImageView iv;int screenWidth,screenHeight;int lastX,lastY; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); iv=(ImageView) findViewById(R.id.imageView1); iv.setOnTouchListener(this); Display dis=this.getWindowManager().getDefaultDisplay(); screenWidth=dis.getWidth(); screenHeight=dis.getHeight(); }@Overridepublic boolean onTouch(View v, MotionEvent event) {switch(event.getAction()){case MotionEvent.ACTION_DOWN:lastX=(int)event.getRawX();lastY=(int)event.getRawY();break;case MotionEvent.ACTION_MOVE:int dx=(int)event.getRawX()-lastX;int dy=(int)event.getRawY()-lastY;int top=v.getTop()+dy;int left=v.getLeft()+dx;if(top<=0){top=0;}if(top>=screenHeight-iv.getHeight()){top=screenHeight-iv.getHeight();}if(left>=screenWidth-iv.getWidth()){left=screenWidth-iv.getWidth();}if(left<=0){left=0;}v.layout(left, top, left+iv.getWidth(), top+iv.getHeight());lastX=(int)event.getRawX();lastY=(int)event.getRawY();break;case MotionEvent.ACTION_UP:break;}return false;}}
工程代碼下載:Android控制項拖動