4

I am dynamically creating a board, made of views that are dynamically set in a relative layout. In my onCreate i call the constructor of my Board class that creates everything:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);
    RelativeLayout boardLayout = (RelativeLayout) findViewById(R.id.layoutBoard);
    board = new Board(this, boardLayout);

}

In my Board class I set the rules for the layer and I also need to set the size of the views I display, and I calculate them starting from the values of boardLayout.getWidth() and boardLayout.getHeight()

Now the problem is that all the actual draw on the screen is performed only after the end of the onCreate method, so at the moment of the creation, the width and height of the layer are zero.

So I decided to set the size using:

    boardLayout.addOnLayoutChangeListener(new RelativeLayout.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right,
                int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                board.setParentLayoutSize(left, top, right, bottom);
        }
    });

Unfortunately this method is available only from API 11 and I must stick to API 10 as a maximum. How could I perform this? Is there a way to listen to layout changes without using this method?

Thank you!

Beppi's
  • 2,089
  • 1
  • 21
  • 38

2 Answers2

4

The most elegant solution is to extend RelativeLayout class, then you can just override onSizeChanged:

protected void onSizeChanged (int w, int h, int oldw, int oldh)

If you need to know the size just after inflate you can try to measure view manually: so call measure(...) than layout(...) and then getMeasuredWidth()/getMeasuredHeight should return the correct size. But this is more tricky, don't use it if you're not sure how it works.

thearti
  • 371
  • 2
  • 6
1

After hours that I could not find anything, I wrote this message and immediately discovered this: How to retrieve the dimensions of a view?

Community
  • 1
  • 1
Beppi's
  • 2,089
  • 1
  • 21
  • 38