【问题标题】:When is a ConstraintLayout drawn in an Activity?什么时候在 Activity 中绘制 ConstraintLayout?
【发布时间】:2018-08-17 19:34:13
【问题描述】:

我有一个带有 ConstraintLayout 的 Android Activity。我想以编程方式获取该 ConstraintLayout 的不同视图的高度和宽度,但我得到 0,因为我在 onCreate() 中执行此操作,并且我猜该布局尚未绘制。

我应该在哪里做?

【问题讨论】:

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


    【解决方案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 操作可确保在视图创建完成后调用其中的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-25
      • 2015-09-26
      • 2014-04-29
      • 1970-01-01
      • 2012-12-29
      • 2022-01-14
      相关资源
      最近更新 更多