什么时候在 Activity 中绘制 ConstraintLayout?
When is a ConstraintLayout drawn in an Activity?
我有一个带有 ConstraintLayout 的 Android Activity。我想以编程方式获取该 ConstraintLayout 的不同视图的高度和宽度,但我得到了 0,因为我在 onCreate() 中进行了操作,我猜布局尚未绘制。
我应该在哪里做?
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 操作确保在视图创建完成后调用其中的代码。
我有一个带有 ConstraintLayout 的 Android Activity。我想以编程方式获取该 ConstraintLayout 的不同视图的高度和宽度,但我得到了 0,因为我在 onCreate() 中进行了操作,我猜布局尚未绘制。
我应该在哪里做?
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 操作确保在视图创建完成后调用其中的代码。