如何将拖动的对象与拖动原点对齐?

时间:2017-12-17 15:30:29

标签: android android-layout android-animation

我有一个内部有五个视图的LinearLayout,它们形成一个1x5网格。

将拖动此LinearLayout。

我目前正在五个视图中的每个视图上设置onTouchListeners,检查该五个拖动源中的哪一个来源并在LinearLayout上调用motionEvent.getAction()。

这是不完美的,因为LinearLayout被它的中心拖动而不是拖动开始点。

有没有什么方法可以在motionEvent的开头变换LinearLayout,这样在拖动时拖动来自的视图是在手指下?

在LinearLayout

中的五个视图中的每一个上设置的MyTouchListener
    private final class MyTouchListener implements View.OnTouchListener {
    //public boolean onTouch(View view, MotionEvent motionEvent) {
    public boolean onTouch(View view, MotionEvent motionEvent) {
        LinearLayout ship = (LinearLayout)view.getParent();
        dragCellIndex = ship.indexOfChild(view);
        dragCellTotal = ship.getChildCount();
        view = ship;

        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {            
            ClipData data = ClipData.newPlainText("", "");
            View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
            view.startDrag(data, shadowBuilder, view, 0);
            view.setVisibility(View.INVISIBLE);
            return true;
        } else {
            return false;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

为此,您需要进行一些数学计算。从motionEvent中检索手指触摸/拖动点X和Y坐标,使用LinearLayout左上角的X和Y坐标计算它们之间的差异,并将它们保存在2个变量中。

这样,当您拖动LinearLayout时,只需将这些变量添加到X和Y坐标,然后将LinearLayout移动到该点。我希望你有这个主意。

我在开发纸牌游戏时使用过这种方法,就像魅力一样。