getWidth()在onCreate中返回0

时间:2014-10-06 16:58:51

标签: java android

我有这段代码:

 @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”。有人可以解释一下活动的生命周期是什么,以及如何测量视图,或者例如如何在开始时直接在活动中创建弹跳球。谢谢!

1 个答案:

答案 0 :(得分:2)

在获取宽度之前,您必须等待绘制布局。绘制完成后,测量宽度并保存宽度,以便调用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()));
    }
});