实现图片的拖拽效果

最近项目里有个模块需要实现拖拽,分析了,发现在不同层内拖拽效果很难实现,要么就是效果体验性很一般。

 

好不容易用了障眼法才解决,呵呵,分享下。

 

package com.nico;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class DragActivity extends Activity {
	ImageView imgview;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		final ImageView img = (ImageView) findViewById(R.id.img);

		final WindowManager wm = this.getWindowManager();
		final WindowManager.LayoutParams wlayout = new WindowManager.LayoutParams();
		wlayout.gravity = Gravity.TOP;

		wlayout.x = 0;
		wlayout.y = 0;

		wlayout.height = WindowManager.LayoutParams.WRAP_CONTENT;
		wlayout.width = WindowManager.LayoutParams.WRAP_CONTENT;
		wlayout.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
				| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
				| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
				| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
		wlayout.format = PixelFormat.TRANSLUCENT;
		wlayout.windowAnimations = 0;

		img.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int act = event.getAction();
				int rawx = (int) event.getRawX()-v.getRight()-v.getWidth();
				int rawy = (int) event.getRawY();
				wlayout.x = rawx;
				wlayout.y = rawy;

				switch (act) {
				case MotionEvent.ACTION_DOWN:

					ImageView newimg = new ImageView(DragActivity.this);
					img.setDrawingCacheEnabled(true);
					Bitmap bt = img.getDrawingCache();
					newimg.setImageBitmap(bt);
					imgview = newimg;
					wm.addView(imgview, wlayout);

					imgview.setVisibility(View.VISIBLE);

					break;
				case MotionEvent.ACTION_MOVE:
//					wlayout.x = rawx;
//					wlayout.y = rawy;
					wm.updateViewLayout(imgview, wlayout);
					break;
				case MotionEvent.ACTION_UP:
					wm.removeView(imgview);
					if (imgview != null) {
						imgview.destroyDrawingCache();
						imgview = null;

					}
					break;
				}

				return true;
			}
		});

	}
}

 

 

你可能感兴趣的:(android,OS,UP)