自由移动的Imageview,并要实现长按后拖动(类似widget),点击可按如下方法自定义控件。
import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.Window; import android.widget.ImageView; /** * * @author EliyetYang * *该类为自定义ImageView,在为该视图添加长按监听,并在监听回调方法中将该类成员变量hadLongClick赋值为true的情况下, *可以实现长按后自由拖动的效果,如添加点击事件,请以该类成员变量hadLongClick为判据,当该值为false时执行回调。 *拖动活点击后该视图将在所有视图最顶层,不会被遮盖。 */ public class MyDragableView extends ImageView { Context mContext; public boolean hadLongClick = false; public MyDragableView(Context context) { super(context); mContext = context; } public MyDragableView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; } public MyDragableView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; } private float x = 0; private float y = 0; private int defaultHeight = 70; // @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); } private int getStatusAndTitleBarHeight() { Activity ac = (Activity) mContext; Rect frame = new Rect(); ac.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; int contentTop = ac.getWindow().findViewById(Window.ID_ANDROID_CONTENT) .getTop(); int titleBarHeight = contentTop - statusBarHeight; return statusBarHeight + titleBarHeight; } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: hadLongClick = false;//在longclick触发前重置判据。 defaultHeight = getStatusAndTitleBarHeight(); x = event.getX(); y = event.getY() + defaultHeight; break; case MotionEvent.ACTION_MOVE: if (hadLongClick) {//当长按后可出发移动效果。 int xx = (int) (event.getRawX() - x); int yy = (int) (event.getRawY() - y); this.layout(xx, yy, xx + getWidth(), yy + getHeight()); } break; case MotionEvent.ACTION_UP: bringToFront();//使该可拖动控件始终在最前端 break; default: break; } return super.onTouchEvent(event); } }
刚刚一段代码没有进行完美的封装,没有强制性,需要主动实现要求。
SVN检出的项目文件需要重新编译Clean下才能跑。
浙公网安备 33010602011771号