Home » Android » android – getLayoutParams returning null?

android – getLayoutParams returning null?

Posted by: admin May 14, 2020 Leave a comment

Questions:

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?

How to&Answers:

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();
}

Answer:

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;
}