【问题标题】:How to get the margins of a View, moved to a position which isn't known at run time如何获取视图的边距,移动到运行时未知的位置
【发布时间】:2016-10-21 08:33:18
【问题描述】:

截至目前,我正在开发一款 Android 应用程序,该应用程序提供了一些培训师可以用来与学员交流的工具,其中一个工具是一个阵容编辑器,它由可拖放的微调器组成*。

*有一个默认的Layout set->football Lineup: 4/4/2

如果用户按下 saveBtn,则阵容将保存为自定义 obj。称为阵容,其中包含 2 个具有 x 和 y 坐标的数组。它在包含一个名为“编辑”的按钮的 Recyclerview 中被表示。通过按下编辑按钮,我想通过将这些 x 和 y 坐标设置为默认编辑模式活动中的微调器来显示保存的阵容。

我的问题是,程序总是返回 .xml 中设置的默认边距。

我使用 .getLeft 和 .getBottom 进行了尝试,您可以在此处看到:

public Lineup saveLineup(){
    int[] x=new int[10];
    int[] y=new int[10];
    LayoutParams[] layouts=new LayoutParams[10];

    for(int i=0; i<10; i++){
        x[i]=positions[i].getLeft();//positions contains all the spinners used in the .xml
        y[i]=positions[i].getBottom();
    }
    Lineup lineup=new Lineup(x,y);
    return lineup;
}

要拖放,我将覆盖 OnTouch 方法,如下所示:

@Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                dX = view.getX() - event.getRawX();
                dY = view.getY() - event.getRawY();
                break;

            case MotionEvent.ACTION_MOVE:

                view.animate()
                        .x(event.getRawX() + dX)
                        .y(event.getRawY() + dY)
                        .setDuration(0)
                        .start();
                break;
            default:
                return false;
        }
        return true;
    }

【问题讨论】:

    标签: android drag-and-drop margins layoutparams


    【解决方案1】:

    使用getLocationOnScreen(int[] outLocation) 代替getLeft()getBottom() 方法来获取视图相对于屏幕的坐标。

    int[] outLocation = new int[2];
    position[i].getLocationOnScreen(outLocation);
    
    int marginleft=outLocation[0];
    int margintop=outLocation[1];
    

    详情请见:https://developer.android.com/reference/android/view/View.html#getLocationOnScreen(int[])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 2011-10-28
      相关资源
      最近更新 更多