Hunt
Hunt

Reputation: 8425

drag n drop textview in android

I want to drag n drop the text view on image in android 2.X

please , look at this image below. alt text

Here, "Blue" color represents the ViewGrop , "White" is ImageView and the image is set on the ImageView. the text written "Fashion" is a TextView.This is how i have implement the structure. Now i want to allow the user to select the TextView and drag it to any part of the image and then drop it over the image at desired position.

As of now for a reference i tried to refer the following url but whenever i use TextView instead of Button things are getting abnormal.

link text

Can anyone give me the road map or example to get it done ?

Upvotes: 11

Views: 6207

Answers (1)

Snailer
Snailer

Reputation: 3839

Instead, try getting your ImageView as a canvas to draw into.

ImageView CanvasView = (ImageView) findViewById(R.id.fashion_pic)

From here you can create your own Bitmap and re-draw it after a TouchEvent. The following snippet contains a necessary work-around for a bug in 2.1 (or 2.2, I can't remember):

public void redrawImage() {

    Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.fashion_pic);
    Bitmap proxy = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Config.ARGB_8888);
    Canvas c = new Canvas(proxy);

    //Here, we draw the background image.
    c.drawBitmap(bm, new Matrix(), null);

    //Here, we draw the text where the user last touched.
    c.drawText("Fashion", someGlobalXvariable, someGlobalYvariable, somePaint);

    CanvasView.setImageBitmap(proxy);
}

Here, you have created a canvas which already has your picture as the background and paints text at an x and y variable. Now, just set an OnTouchListener:

CanvasView.setOnTouchListener( new OnTouchListener(){

    public boolean onTouch(View v, MotionEvent e) {

        someGlobalXvariable = e.getX();
        someGlobalYvariable = e.getY();
        redrawImage();
        return true;
    }
});

As you can see, the listener automatically updates your image when it is touched, and the text will follow the user's finger. Since you're using a Bitmap as your canvas, you can also add support for saving/loading an image if your app wants to have that kind of functionality.

Edit: It may be more performance-friendly if you move lines 1-3 from redrawImage() and place them elsewhere, setting those objects as global objects. I'll let you tinker with that.

Upvotes: 10

Related Questions