vcmkrtchyan
vcmkrtchyan

Reputation: 2626

Android ImageView drag and drop positioning

Here is my code

public class MainActivity extends Activity {

    int screenWidth;
    int screenHeight;

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

        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

        screenWidth = displaymetrics.widthPixels;
        screenHeight = displaymetrics.heightPixels;

        final ImageView img = (ImageView) findViewById(R.id.imageView1);

        img.setOnTouchListener(new View.OnTouchListener() {

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

                        if (x_cord > screenWidth) {
                            x_cord = screenWidth;
                        }
                        if (y_cord > screenHeight) {
                            y_cord = screenHeight;
                        }

                        layoutParams.leftMargin = x_cord;
                        layoutParams.topMargin = y_cord;

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

But when i'm running my app and try to drag and drop my circle image, the circle image starts blinking very vast, it does not drag normally. Here is the video demonstrating that.

https://www.youtube.com/watch?v=sGtza5HKMOI

Please explain what am I doing wrong.

Thanks in advance.

Upvotes: 1

Views: 1261

Answers (1)

vcmkrtchyan
vcmkrtchyan

Reputation: 2626

After a little brute force, I came up to a solution like this, maybe it can be useful for someone.

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

            img.setX(x_cord - 150);
            img.setY(y_cord - 230);
            break;
        default:
            break;
    }
    return true;
}

The numbers 150 and 230 are just because the positioning starts from the top left angle of the imageview, I was too lazy to fix out the actual touch location within the imageview and to set the positioning relative to that coordinates. :)

Upvotes: 1

Related Questions