使用样式和主题为自定义属性创建默认值

hap*_*ude 15 android declare-styleable

我有几个自定义View,我在其中创建了自定义的可样式属性,这些属性在xml布局中声明并在视图的构造函数中读入.我的问题是,如果我在xml中定义布局时没有为所有自定义属性提供显式值,我如何使用样式和主题来获得将传递给我View的构造函数的默认值?

例如:

attrs.xml:

<declare-styleable name="MyCustomView">
    <attr name="customAttribute" format="float" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

layout.xml(android:为简单起见,删除了标签):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.mypackage" >

    <-- Custom attribute defined, get 0.2 passed to constructor -->

    <com.mypackage.MyCustomView
        app:customAttribute="0.2" />

    <-- Custom attribute not defined, get a default (say 0.4) passed to constructor -->

    <com.mypackage.MyCustomView />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

hap*_*ude 13

在做了更多的研究之后,我意识到可以在构造函数中为View自己设置默认值.

public class MyCustomView extends View {

    private float mCustomAttribute;

    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray array = context.obtainStyledAttributes(attrs,
            R.styleable.MyCustomView);
        mCustomAttribute = array.getFloat(R.styleable.MyCustomView_customAttribute,
            0.4f);

        array.recycle();
    }
}
Run Code Online (Sandbox Code Playgroud)

也可以从xml资源文件加载默认值,该文件可以根据屏幕大小,屏幕方向,SDK版本等进行更改.

  • 更重要的是,如果不存在默认值的第二个参数(如getString()),您可以检查它是否为null,然后在运行时指定默认值. (2认同)