tags:

views:

205

answers:

1

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?

A: 

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();
}
Samuh
Thanks for the help.All I really needed was the XML attribute value which I could obtain from the AttributeSet in the constructor. Here's my (ugly) solution:String ns = "http://schemas.android.com/apk/res/android";String v = attrs.getAttributeValue(ns, "layout_height");// Convert "270px" to "270"v = v.replace("px", "");// At runtime this value is "270.0"v = v.replace(".0", ""); int h = Integer.parseInt(v);
tronman