何时在Activity中绘制ConstraintLayout?

时间:2018-03-09 09:11:18

标签: android android-layout android-constraintlayout activity-lifecycle

我有一个带有ConstraintLayout的Android Activity。我想以编程方式获得ConstraintLayout的不同视图的高度和宽度,但是我得到0,因为我在onCreate()中执行它,我猜想还没有绘制布局。

我应该在哪里做?

先谢谢!

1 个答案:

答案 0 :(得分:1)

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
}

使用post操作可确保在视图创建完成后调用其中的代码。