2
我正在對圖像進行拖放操作。我通過擴展View
開發了MyView
類,我重寫了onDraw
方法,現在我可以拖動單個圖像。如何通過在Android中擴展View來拖動多個圖像?
但是,當涉及到多個圖像我無法拖動所需的圖像。當我嘗試這樣做時,每個圖像都被拖拽。
這裏是我的代碼:
公共類家庭延伸活動{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(getApplicationContext()));
}
public static class MyView extends View{
private Drawable mIcon,mIcon1;
private TextView tv;
private float mLastTouchX;
private float mLastTouchY;
private float mPosX;
private float mPosY;
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
mIcon=getResources().getDrawable(R.drawable.icon);
mIcon.setBounds(0,0,mIcon.getIntrinsicWidth(),mIcon.getIntrinsicHeight());
mIcon1=getResources().getDrawable(R.drawable.icon);
mIcon1.setBounds(40,40,150,100);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.translate(mPosX,mPosY);
tv.draw(canvas);
mIcon.draw(canvas);
mIcon1.draw(canvas);
canvas.restore();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN: {
final float x = event.getX();
final float y = event.getY();
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = event.getX();
final float y = event.getY();
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
mPosX += dx;
mPosY += dy;
mLastTouchX = x;
mLastTouchY = y;
invalidate();
break;
}
}
return true;
}
}
}
感謝