Search code examples
androidandroid-layoutandroid-constraintlayoutactivity-lifecycle

When is a ConstraintLayout drawn in an Activity?


I have an Android Activity with a ConstraintLayout. I want to get the heights and widths of different views of that ConstraintLayout programatically, but I get 0's because I do it in onCreate() and I guess that the Layout hasn't been drawn yet.

Where should I do it?


Solution

  • int height;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        final View myView = findViewById(R.id.myView);
        myView.post(new Runnable(){
            @Override
            public void run() {
                //do the operations related to height here
                //this method is asynchronous
                height = myView.getHeight();
                Log.d(TAG, "Height inside runnable is : "+height); //this will be correct height
            }
        });
        Log.d(TAG, "Height is : "+height); //this will be zero because above method is asynchronous
    }
    

    Using the post operation makes sure that the code inside it are called once the view creation is completed.