可移动控件:
效果图:
获取屏幕的宽高:
DisplayMetrics dm = getResources().getDisplayMetrics();
screenWidth = dm.widthPixels;
screenHeight = dm.heightPixels - 50;
ImageView imageView = (ImageView)findViewById(R.id.spirit_img);
imageView.setOnTouchListener(this);
onTouch设定:
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action){
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 left = v.getLeft() + dx;
int top = v.getTop() + dy;
int right = v.getRight() + dx;
int bottom = v.getBottom() + dy;
if(left < 0){
left = 0;
right = left + v.getWidth();
}
if(right > screenWidth){
right = screenWidth;
left = right - v.getWidth();
}
if(top < 0){
top = 0;
bottom = top + v.getHeight();
}
if(bottom > screenHeight){
bottom = screenHeight;
top = bottom - v.getHeight();
}
v.layout(left, top, right, bottom);
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
break;
}
return false;
}
layout的办法有一个问题,viewgroup里面的其他东西刷新,imageview就会归位。