简单拖动效果(带Cache,需要完善)
如何去实现一个具有幻象的拖拽效果?
所谓”幻象“就是当你按下去拖动一个View时,View本身不动,拖动的是这个View的复制品,当抬起时真正的View才显示到拖动的地方。
复制品很容易解决,2句代码就可以了:
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
package com.ql.app;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;import android.widget.Button;import android.widget.FrameLayout;import android.widget.ImageView;import android.widget.FrameLayout.LayoutParams;/** * 参考:http://techdroid.kbeanie.com/2010/04/simple-drag-n-drop-on-android.html * @author admin * */public class App extends Activity implements OnTouchListener{private final static int START_DRAGGING = 0;private final static int STOP_DRAGGING = 1;private Button btn;private FrameLayout layout;private int status;private LayoutParams params;private ImageView image;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);layout = (FrameLayout) findViewById(R.id.layout);// layout.setOnTouchListener(this);btn = (Button) findViewById(R.id.btn);btn.setDrawingCacheEnabled(true);btn.setOnTouchListener(this);params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);}@Overridepublic boolean onTouch(View view, MotionEvent me) {switch (me.getAction()) {case MotionEvent.ACTION_DOWN:status = START_DRAGGING;image = new ImageView(this);image.setImageBitmap(btn.getDrawingCache());layout.addView(image, params);break;case MotionEvent.ACTION_MOVE:if (status == START_DRAGGING) {image.setPadding((int) me.getRawX(), (int) me.getRawY(), 0, 0);image.invalidate();}break;case MotionEvent.ACTION_UP:status = STOP_DRAGGING;Log.i("Drag", "Stopped Dragging");//layout.removeView(image);break;default:break;}return false;}}
<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent" android:layout_height="fill_parent"android:id="@+id/layout"><Button android:layout_width="wrap_content"android:layout_height="wrap_content" android:id="@+id/btn"android:text="Drag Me"/></FrameLayout>