如何从具有自定义元素的布局中获取默认参数。
带有自定义元素的活动
<com.example.custombutton.CustomButton
android:id="@+id/jjs"
android:layout_width="match_parent"
android:layout_height="match_parent"
custom:text_size="199"/>
自定义元素类
public CustomButton(Context context, AttributeSet attributeSet){
super(context, attributeSet);
mContext = context;
TypedArray attributes = context.obtainStyledAttributes(attributeSet, R.styleable.CustomButtonAttrs);
int mRadiusHeight = attributes.getInteger(R.styleable.CustomButtonAttrs_android_layout_width, 0);
Log.i("CustomButton", mRadiusHeight + "");
}
我不知道这有什么帮助,但我会把它留在这里。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomButtonAttrs">
<attr name="text_size" format="integer"/>
</declare-styleable>
</resources>
你做的一切都是对的,但有一件事:由于视图属性值设置
match_parent
为 ,并且在调用构造函数的那一刻,这个视图还没有被绘制,它将mRadiusHeight
是0
。getWidth()
可以分别使用 和 方法获得视图的宽度(以及高度)getHeight()
。视图的实际宽度和高度只有在绘制后才可用。例如,方法中调用的
getWidth()
and方法将返回空值,因为此时视图尚未绘制。getHeight()
onCreate(...)
您可以跟踪视图呈现的时刻,例如,使用
OnGlobalLayoutListener
:收到查看参数后,不要忘记删除已安装的
OnGlobalLayoutListener
.