Android ImageView拖放定位

时间:2015-05-12 20:49:42

标签: android drag-and-drop android-imageview

这是我的代码

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

但是,当我正在运行我的应用程序并尝试拖放我的圆形图像时,圆形图像开始闪烁非常大,它不会正常拖动。以下是视频演示。

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

请解释我做错了什么。

提前致谢。

1 个答案:

答案 0 :(得分:1)

经过一番蛮力,我找到了这样的解决方案,也许对某人有用。

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

数字150和230只是因为定位从图像视图的左上角开始,我太懒了,无法修复图像视图中的实际触摸位置并设置相对位置到那个坐标。 :)