实现效果,Buttton在屏幕范围内到处拖动,但不会拖出屏幕,代码如下:
运行效果如下:
[img]http://dl.iteye.com/upload/attachment/350275/15afacd5-a847-3604-88eb-44f22afb86f4.png[/img]
[img]http://dl.iteye.com/upload/attachment/350277/e8c3f34b-9074-3425-9e8d-cf435dc142ad.png[/img]
[img]http://dl.iteye.com/upload/attachment/350279/2061120c-9ab5-32b6-a614-fb50ec9aac33.png[/img]
public class DraftTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DisplayMetrics dm=getResources().getDisplayMetrics();
final int screenWidth=dm.widthPixels;
final int screenHeight=dm.heightPixels-50;
final Button b=(Button)findViewById(R.id.btn);
b.setOnTouchListener(new OnTouchListener(){
int lastX,lastY;
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int ea=event.getAction();
Log.i("TAG", "Touch:"+ea);
switch(ea){
case MotionEvent.ACTION_DOWN:
lastX=(int)event.getRawX();//获取触摸事件触摸位置的原始X坐标
lastY=(int)event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int dx=(int)event.getRawX()-lastX;
int dy=(int)event.getRawY()-lastY;
int l=v.getLeft()+dx;
int b=v.getBottom()+dy;
int r=v.getRight()+dx;
int t=v.getTop()+dy;
//下面判断移动是否超出屏幕
if(l<0){
l=0;
r=l+v.getWidth();
}
if(t<0){
t=0;
b=t+v.getHeight();
}
if(r>screenWidth){
r=screenWidth;
l=r-v.getWidth();
}
if(b>screenHeight){
b=screenHeight;
t=b-v.getHeight();
}
v.layout(l, t, r, b);
lastX=(int)event.getRawX();
lastY=(int)event.getRawY();
Toast.makeText(DraftTest.this,
"当前位置:"+l+","+t+","+r+","+b,
Toast.LENGTH_SHORT).show();
v.postInvalidate();
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}});
}
}
运行效果如下:
[img]http://dl.iteye.com/upload/attachment/350275/15afacd5-a847-3604-88eb-44f22afb86f4.png[/img]
[img]http://dl.iteye.com/upload/attachment/350277/e8c3f34b-9074-3425-9e8d-cf435dc142ad.png[/img]
[img]http://dl.iteye.com/upload/attachment/350279/2061120c-9ab5-32b6-a614-fb50ec9aac33.png[/img]