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

16

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

例如:

attrs.xml:

<declare-styleable name="MyCustomView">
    <attr name="customAttribute" format="float" />
</declare-styleable>

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>
1个回答

15

经过更多的研究,我意识到可以在 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();
    }
}

默认值也可以从一个XML资源文件中加载,该文件可根据屏幕尺寸、屏幕方向、SDK版本等进行变化。


2
此外,如果没有第二个参数来指定默认值(例如getString()),您可以在运行时检查其是否为null,然后指定默认值本身。 - renatoaraujoc
让用户在输入属性时选择一些特定的值[只允许可接受的选项],并将它们作为选项显示出来。在Android的默认和已知组件中,当你想在<EditText>中使用<android:inputType = "textPassword"> [除了<textPassword>,你还可以选择其他选项],或者在<ImageView>中使用<android:scaleType = "fitCenter"> [除了<centerinside>,你还可以选择其他选项],它们会以下拉列表的形式出现。 - Abhinav Saxena

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