androidlocationlayoutparams

getLocationInWindow not change after change LayoutParams


I have a view like this:

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

I get the global position twice. Before changing the view size and After changing the view size.

CODE:

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

When I see the logs, the location is the same.

What is wrong?


Solution

  • Basically, you're not waiting for the UI to get updated and for the layout constraints to be implemented. Try posting it from Handler and you'll get your expected results.

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