有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java getWidth()在onCreate中返回0

我有以下代码:

 @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) 个答案

  1. # 1 楼答案

    在获得宽度之前,必须等待绘制布局。绘制时,会对其进行测量并保存宽度,以便您可以调用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()));
        }
    });