在onResume视图为什么调用的getWidth()()返回0? [英] Why does calling getWidth() on a View in onResume() return 0?

查看:207
本文介绍了在onResume视图为什么调用的getWidth()()返回0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过的一切说,你不能叫的getWidth()的getHeight()查看在构造函数中,但我打电话给他们在 onResume()。不应在屏幕的布局已经被绘制话?

  @覆盖
保护无效onResume(){
    super.onResume();    populateData();
}私人无效populateData(){
    测试的LinearLayout =(的LinearLayout)findViewById(R.id.myview);
    双widthpx = test.getWidth();
}


解决方案

一个观点仍没有绘制时onResume被调用,所以它的宽度和高度都为0。你可以捕捉时,它的大小使用OnGlobalLayoutListener改变() 。 的Andr​​oid得到回报宽度0 可能会有所帮助。

  yourView.getViewTreeObserver()。addOnGlobalLayoutListener(新OnGlobalLayoutListener(){    @覆盖
    公共无效onGlobalLayout(){        //删除布局监听器,以避免多次调用
        如果(Build.VERSION.SDK_INT< Build.VERSION_ codeS.JELLY_BEAN){
            。yourView.getViewTreeObserver()removeGlobalOnLayoutListener(本);
        }
        其他{
            。yourView.getViewTreeObserver()removeOnGlobalLayoutListener(本);
        }        populateData();
    }
});

Everything I've read says you can't call getWidth() or getHeight() on a View in a constructor, but I'm calling them in onResume(). Shouldn't the screen's layout have been drawn by then?

@Override
protected void onResume() {
    super.onResume();

    populateData();
}

private void populateData() {
    LinearLayout test = (LinearLayout) findViewById(R.id.myview);
    double widthpx = test.getWidth();
}

解决方案

A view still hasn't drawn when onResume is called, so its width and height are 0. You can "catch" when its size changed using OnGlobalLayoutListener(). Android get width returns 0 might be helpful.

yourView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {

        // Removing layout listener to avoid multiple calls
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
        else {
            yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }

        populateData();
    }
});

这篇关于在onResume视图为什么调用的getWidth()()返回0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆