在我的应用程序中,我需要根据另一个视图的宽度来设置视图的宽度。但是,Activity的onCreate()方法似乎并不是这样做的好地方。视图的宽度通过getWidth()返回0。其他方法onStart()和onResume()也有类似的行为。
我想知道是否有任何方法是在一个视图被初始化后调用的?或者,还有别的方法可以实现我的目标吗?
发布于 2013-12-18 21:01:38
在onGlobalLayoutListener方法中声明onCreate:
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);
}
}); 发布于 2013-12-18 20:45:18
试试onGlobalLayoutListener。获取主根视图的实例,然后只使用addOnGlobalLayoutListener()方法。
当您的视图已经在屏幕上创建和度量时,您将收到回调:
http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html
https://stackoverflow.com/questions/20667976
复制相似问题