0

I have this code :

 @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);

}

The problem is that in log it says " 0 ". Can someone explain me what is the lifecycle of an activity and how do you measure a view or for example how do you create a bouncing ball in an activity directly on start. Thanks!

1 Answers1

2

You have to wait for the layout to be drawn before getting the width. When drawn it's measured and the width is saved so you can call getWidth. You can add a layout listener to wait for the view to be drawn:

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()));
    }
});
Simas
  • 43,548
  • 10
  • 88
  • 116