Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getLayoutParams returning null?

Tags:

android

I've created a class that extends a View:

public class BoardView extends View  {

and I've specified the width and height of the BoardView in the application's main.xml file:

  <mypackage.BoardView
        android:id="@+id/board"         
        android:layout_width="270px" 
        android:layout_height="270px" /> 

I'm trying to get the width and height from a function that is called from the BoardView's constructor. Here's what I'm doing:

ViewGroup.LayoutParams p = this.getLayoutParams();
int h = p.height;

but getLayoutParams is always returning null. Any idea why this isn't working?

like image 974
tronman Avatar asked Jan 13 '10 23:01

tronman


2 Answers

After the view is added to its parent the layout parameters are available. Try moving your code from the view constructor to onAttachedToWindow() because getLayoutParams() won't return null there.

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    assert getLayoutParams() != null;
}
like image 63
Zsolt Safrany Avatar answered Nov 06 '22 13:11

Zsolt Safrany


I am not sure that layout parameters(i.e. instance of LayoutParams) will be available inside constructor of the View. I think, it will only be available after "layout" passes have been made. Read about How Android draws views here. Also, this thread tries to pin point when exactly should you expect to get Measured dimensions of a View.

Note that if you are interested in just getting the attribute values passed via layout XML, you can use AttributeSet instance passed as an argument to your constructor.

public MyView(Context context, AttributeSet attrs){
// attrs.getAttributeCount();
// attrs.getAttributeXXXvalue();
}
like image 28
Samuh Avatar answered Nov 06 '22 13:11

Samuh