我需要ScrollView
在活动启动期间检索布局 xml 文件中定义的高度。这是实现这一点的最佳实践。我试过将代码放在onCreate()
,onStart()
和onResume()
. All 在启动时将高度设为 0。有没有类似onFinishInflate()
活动的方法?
这是我的代码:
myScroll=(ScrollView) findViewById(R.id.ScrollView01);
int height=myScroll.getHeight();
我需要ScrollView
在活动启动期间检索布局 xml 文件中定义的高度。这是实现这一点的最佳实践。我试过将代码放在onCreate()
,onStart()
和onResume()
. All 在启动时将高度设为 0。有没有类似onFinishInflate()
活动的方法?
这是我的代码:
myScroll=(ScrollView) findViewById(R.id.ScrollView01);
int height=myScroll.getHeight();
你可以这样做:
获取对 ScrollView 的最终引用(在 onGlobalLayout() 方法中访问)。接下来,从 ScrollView 中获取 ViewTreeObserver,并添加一个 OnGlobalLayoutListener,覆盖 onGLobalLayout 并在此侦听器中获取测量值。
final ScrollView myScroll = (ScrollView)findViewById(R.id.my_scroll);
ViewTreeObserver vto = myScroll.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
LayerDrawable ld = (LayerDrawable)myScroll.getBackground();
height = myScroll.getHeight();
width=myScroll.getHeight();
ViewTreeObserver obs = myScroll.getViewTreeObserver();
obs.removeOnGlobalLayoutListener(this);
}
});
在此线程中查看更多信息:
您需要在执行布局后查询视图边界。建议的地方是onWindowFocusChanged(boolean)
。有关更多信息,请参阅此问题:如何获取视图的绝对坐标
此外,如果你敢于扩展你的 Layout 类,例如创建一个等的子类LinearLayout
,你可以用这种方式覆盖它的 onLayout():
@Override
public void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
myScroll=(ScrollView) findViewById(R.id.ScrollView01);
int height=myScroll.getHeight();
}