更改 LayoutParams 后 getLocationInWindow 不会更改

getLocationInWindow not change after change LayoutParams

我有这样的看法:

<View 
    android:layout_width="50dp"
    android:layout_height="50dp"/>

我获得了两次全局位置。更改视图大小之前和更改视图大小之后。

代码:

private void getViewPosition(View view){
    int[] firstPosition = new int[2];
    int[] secondPosition = new int[2];
    RelativeLayoutParams lp = (RelativeLayoutParams)view.getLayoutParams();

    view.getLocationInWindow(firstPosition);

    lp.width = 150;
    lp.height = 150;
    view.setLayoutParams(lp);

    view.getLocationInWindow(secondPosition);
    Log.i("FirstLocation", firstPosition[0]);
    Log.i("SecondLocation", secondPosition[0];
}

当我看到日志时,位置是相同的。

怎么了?

基本上,您不需要等待 UI 更新和实施布局约束。 尝试从 Handler 发布它,您会得到预期的结果。

private void getViewPosition(final View view){
    final int[] firstPosition = new int[2];
    final int[] secondPosition = new int[2];
    ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams )view.getLayoutParams();

    view.getLocationInWindow(firstPosition);

    lp.width = 150;
    lp.height = 150;
    view.setLayoutParams(lp);

    new Handler().post(new Runnable() {
        @Override
        public void run() {
            view.getLocationInWindow(secondPosition);
            Log.i("FirstLocation", String.valueOf(firstPosition[0]));
            Log.i("SecondLocation", String.valueOf(secondPosition[0]));
        }
    });
}