开发者

how to drag an image by touching in android? [duplicate]

This question already has answers here: Touch and drag image in android (2 answers) Closed 9 years ago. 开发者_开发技巧

how to drag an image by touching in android? Please Help me with a sample code.


package com.examples.Touchmoveimage;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;

public class Touchmoveimage extends Activity {

    int windowwidth;
    int windowheight;

    private LayoutParams layoutParams;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        windowwidth = getWindowManager().getDefaultDisplay().getWidth();
        windowheight = getWindowManager().getDefaultDisplay().getHeight();
        final ImageView balls = (ImageView) findViewById(R.id.ball);

        balls.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                LayoutParams layoutParams = (LayoutParams) balls.getLayoutParams();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int x_cord = (int) event.getRawX();
                        int y_cord = (int) event.getRawY();

                        if (x_cord > windowwidth) {
                            x_cord = windowwidth;
                        }
                        if (y_cord > windowheight) {
                            y_cord = windowheight;
                        }

                        layoutParams.leftMargin = x_cord - 25;
                        layoutParams.topMargin = y_cord - 75;

                        balls.setLayoutParams(layoutParams);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }
}

works good!!


You need to read about Gestures especially Scroll - which is drag in Android - and Fling.

I recommend to you this tutorial. Its exactly what you are looking for.


There is no direct way to do drag and drop in Android. You have to write some classes. Look into DragController.java, DragLayer.java in Launcher project.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜