This question already has answers here:
View's getWidth() and getHeight() returns 0
                                
                                    (17个答案)
                                
                        
                5年前关闭。
            
        

我有这个代码:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    content = (RelativeLayout) findViewById(R.id.content);
    ball = (Ball) findViewById(R.id.ball);
    txt = (TextView) findViewById(R.id.textView);
    txt.setVisibility(View.GONE);
    Log.d("sizes", String.valueOf(content.getWidth()));
    ball.setOnTouchListener(this);

}


问题在于日志中显示“ 0”。有人可以向我解释一个活动的生命周期是什么,以及如何测量视图,例如如何在活动开始时直接在活动中创建一个弹跳球。谢谢!

最佳答案

您必须等待绘制布局才能获取宽度。绘制时将对其进行测量并保存宽度,以便调用getWidth。您可以添加布局侦听器以等待绘制视图:

final RelativeLayout content = (RelativeLayout) findViewById(R.id.content);
content.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        content.removeOnLayoutChangeListener(this);
        Log.d("sizes", String.valueOf(content.getWidth()));
    }
});

关于java - getWidth()在onCreate中返回0 ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26221081/

10-10 06:14