【发布时间】:2018-08-17 19:34:13
【问题描述】:
我有一个带有 ConstraintLayout 的 Android Activity。我想以编程方式获取该 ConstraintLayout 的不同视图的高度和宽度,但我得到 0,因为我在 onCreate() 中执行此操作,并且我猜该布局尚未绘制。
我应该在哪里做?
【问题讨论】:
标签: android android-layout android-constraintlayout activity-lifecycle
我有一个带有 ConstraintLayout 的 Android Activity。我想以编程方式获取该 ConstraintLayout 的不同视图的高度和宽度,但我得到 0,因为我在 onCreate() 中执行此操作,并且我猜该布局尚未绘制。
我应该在哪里做?
【问题讨论】:
标签: android android-layout android-constraintlayout activity-lifecycle
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 操作可确保在视图创建完成后调用其中的代码。
【讨论】: