假设您想要创建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
子类的大小,这样我就不需要了仅仅因为这个而将两个班级结合在一起?
答案 0 :(得分:1)
您可以覆盖onLayout method或onSizeChanged。 Also you can use ViewTreeOserver.如果您想了解onMeasure方法的结果,请在onMeasure中使用getMeasuredWidth/Height
而不是getWidth/Height
。