在我的应用中,我需要根据另一个视图的宽度设置视图的宽度。但是,Activity的onCreate()方法似乎不是一个好的地方。视图的宽度通过getWidth()返回0.其他方法onStart()和onResume()的行为也类似。
我想知道在初始化视图后调用的Activity上是否有任何方法?或者,还有另一种方法可以实现我的目标。
答案 0 :(得分:3)
试试onGlobalLayoutListener
。获取主根视图的实例,然后使用addOnGlobalLayoutListener()
方法。
当您的观点已在屏幕上创建和测量时,您将收到回调:
http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html
答案 1 :(得分:0)
在onCreate方法中声明onGlobalLayoutListener:
View firstView = (View) findViewById(R.id.firstView);
View secondView = (View) findViewById(R.id.secondView);
firstView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Ensure you call it only once :
firstView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = firstView.getWidth();
int height = firstView.getHeight();
// set dimensions of another view with that dimensions
secondView.setWidth(width);
secondView.setHeight(height);
}
});