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

标签 android declare-styleable

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

例如:

属性.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>

最佳答案

经过更多研究,我意识到可以在构造函数中为 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 版本等而有所不同。

关于android - 使用样式和主题为自定义属性创建默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10860177/

相关文章:

android - 验证 Android 位图是 GrayScale

java - 如何为不同的标签声明几个具有相同名称的样式属性?

android - 错误 : In <declare-styleable> MenuView, 找不到属性 android:preserveIconSpacing

android - declare-stylable 名称如何链接到使用其属性的 View ?

android - HashMap 和谷歌地图

android - 如何维护复选框的状态

android - 如何在 Android 中创建一个标签为 "@"的按钮?

Android自定义布局属性 "reference attribute"格式?

android - 如何使用 | 生成枚举值在他们中

java - Libgdx Scene2D 表背景图像未显示