getLayoutParams返回null?

10

我创建了一个扩展了View的类:

public class BoardView extends View  {

我已在应用程序的main.xml文件中指定了BoardView的宽度和高度:

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

我正在尝试从一个在BoardView构造函数中调用的函数中获取宽度和高度。这是我的做法:

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

但是getLayoutParams总是返回null,你知道为什么不起作用吗?

2个回答

18

将视图添加到其父项后,布局参数将可用。尝试将代码从视图构造函数移动到onAttachedToWindow(),因为getLayoutParams()在那里不会返回null

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    assert getLayoutParams() != null;
}

13

我不确定View的构造函数中是否会提供布局参数(即LayoutParams的实例)。我认为只有在“layout”传递之后才会提供它。阅读这里了解有关Android如何绘制视图的更多信息。此外,此线程试图确定您应该何时期望获得View的测量尺寸。

请注意,如果您仅对通过布局XML传递的属性值感兴趣,则可以使用作为构造函数参数传递的AttributeSet实例。

public MyView(Context context, AttributeSet attrs){
// attrs.getAttributeCount();
// attrs.getAttributeXXXvalue();
}

2
感谢您的帮助。我所需要的就是XML属性值,这可以从构造函数中的AttributeSet中获取。以下是我的(丑陋的)解决方案:String ns = "http://schemas.android.com/apk/res/android"; String v = attrs.getAttributeValue(ns, "layout_height");// 将“270px”转换为“270” v = v.replace("px", "");// 在运行时,该值为“270.0” v = v.replace(".0", ""); int h = Integer.parseInt(v); - tronman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接