应用程序启动时读取布局大小

JiT*_*HiN 5 android android-layout android-scrollview

我需要ScrollView在活动启动期间检索布局xml文件中定义的高度.哪个是实现此目的的最佳实践.我试过把代码放在里面onCreate(),onStart()然后onResume().All在启动时将高度设为0.是否有像活动一样onFinishInflate()的方法?

这是我的代码:

myScroll=(ScrollView) findViewById(R.id.ScrollView01);
int height=myScroll.getHeight();
Run Code Online (Sandbox Code Playgroud)

Anu*_*kur 6

你可以这样做:

获取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);
    }

});
Run Code Online (Sandbox Code Playgroud)

在这个帖子中看到更多:

如何检索视图的尺寸?