Subclassing RelativeLayout |如何/在哪里获得其在课堂上的大小?

时间:2013-11-26 14:49:53

标签: android size relativelayout

假设您想要创建RelativeLayout的子类,并且在类定义中要获取其宽度和高度。 (子类通过xml添加到应用程序,match_parent,match_parent)。

我尝试过以下代码,但它让我感到很满意:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // TODO Auto-generated method stub
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    Toast.makeText(context, "" + this.getWidth(), Toast.LENGTH_SHORT).show();
}

这给了我-1:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // TODO Auto-generated method stub
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    Toast.makeText(context, "" + this.getLayoutParams().width, Toast.LENGTH_SHORT).show();
}

那么我的选择是什么,或onMeasure()仅适用于anroid.view.View的子类?

编辑:我知道我可以在onWindowFocusChanged()中调用Activity,但是我可以在其类定义中获得RelativeLayout子类的大小,这样我就不需要了仅仅因为这个而将两个班级结合在一起?

1 个答案:

答案 0 :(得分:1)

您可以覆盖onLayout method或onSizeChanged。 Also you can use ViewTreeOserver.如果您想了解onMeasure方法的结果,请在onMeasure中使用getMeasuredWidth/Height而不是getWidth/Height