我的布局中有一个ImageView,我想在任何地方自由移动它。我找到了一些关于使用OnTouchListener操作移动它的教程(我已经按照这种方式完成了我的工作,但我不喜欢它),有些人建议使用drag and drop api
(Android 3+ api)但是我不能按照我想要的方式实现它(我的意思是没有目标,拖放api 想要拖动视图的目标)
任何人都可以提供示例吗? ( Drag and Drap API的示例)
答案 0 :(得分:0)
imageiew.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
drag(event, v);
return true;
}
});
然后
public void drag(MotionEvent event, View v)
{
RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) v.getLayoutParams();
switch(event.getAction())
{
case MotionEvent.ACTION_MOVE:
{
params.topMargin = (int)event.getRawY() - (v.getHeight());
params.leftMargin = (int)event.getRawX() - (v.getWidth()/2);
v.setLayoutParams(params);
break;
}
case MotionEvent.ACTION_UP:
{
params.topMargin = (int)event.getRawY() - (v.getHeight());
params.leftMargin = (int)event.getRawX() - (v.getWidth()/2);
v.setLayoutParams(params);
break;
}
case MotionEvent.ACTION_DOWN:
{
v.setLayoutParams(params);
break;
}
}
基于哦here
答案 1 :(得分:0)
你可以试试这个
img.setOnTouchListener(new OnTouchListener()
{
PointF DownPT = new PointF(); // Record Mouse Position When Pressed Down
PointF StartPT = new PointF(); // Record Start Position of 'img'
@Override
public boolean onTouch(View v, MotionEvent event)
{
int eid = event.getAction();
switch (eid)
{
case MotionEvent.ACTION_MOVE :
PointF mv = new PointF( event.getX() - DownPT.x, event.getY() - DownPT.y);
img.setX((int)(StartPT.x+mv.x));
img.setY((int)(StartPT.y+mv.y));
StartPT = new PointF( img.getX(), img.getY() );
break;
case MotionEvent.ACTION_DOWN :
DownPT.x = event.getX();
DownPT.y = event.getY();
StartPT = new PointF( img.getX(), img.getY() );
break;
case MotionEvent.ACTION_UP :
// Nothing have to do
break;
default :
break;
}
return true;
}
});
我是从here
得到的