可自由拖动的ImageView
package com.ywm.myView; 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; /** * 可自由拖动的ImageView * * @author wey * */ public class DragableView extends ImageView { public DragableView(Context context) { super(context); mContext = context; // TODO Auto-generated constructor stub } private Context mContext; public DragableView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; } public DragableView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; } private float x = 0; private float y = 0; private int defaultHeight = 70; // @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); } /** * 获得状态栏和标题栏的高度 * * @return */ 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(); // statusBarHeight是上面所求的状态栏的高度 int titleBarHeight = contentTop - statusBarHeight; // 标题栏高度 return statusBarHeight + titleBarHeight; } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub switch (event.getAction()) { case MotionEvent.ACTION_DOWN: defaultHeight = getStatusAndTitleBarHeight(); // 触控笔按下 x = event.getX(); // 得到X坐标 y = event.getY() + defaultHeight; // 要减去标题栏和状态栏高度 // break; case MotionEvent.ACTION_MOVE: int xx = (int) (event.getRawX() - x); int yy = (int) (event.getRawY() - y); this.layout(xx, yy, xx + getWidth(), yy + getHeight()); // ViewGroup.LayoutParams lp = new LayoutParams( // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, // (int) event.getRawX() - x, (int) event.getRawY() - y); // this.setLayoutParams(lp); break; default: break; } return true; } }
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28