如何通过在Android中扩展View来拖动多个图像?

时间:2011-06-03 08:06:18

标签: android

我正在处理拖放图片。我通过扩展MyView开发了View类,并且我已经覆盖了onDraw方法,现在我可以拖动单个图像。

但是当谈到多个图像时,我无法拖动所需的图像。当我尝试这样做时,每个图像都被拖动。

这是我的代码:

public class Home扩展活动{

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;
    }
}

}

由于

1 个答案:

答案 0 :(得分:2)

请添加一些代码,但是当您这样做时,如果您将所有图像添加到同一视图中,则必须使用图像创建不同的MyView实例以分离拖动操作。