本文介绍了如何在代码中获取在 attrs.xml 中创建的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个带有声明样式属性的自定义视图(在此处找到)枚举类型.在 xml 中,我现在可以为我的自定义属性选择枚举条目之一.现在我想创建一个方法来以编程方式设置这个值,但我无法访问枚举.

I created a custom View (find it here) with an declare-styleable attribute of type enum. In xml I can now choose one of the enum entries for my custom attribute. Now I want to create an method to set this value programmatically, but I can not access the enum.

attr.xml

<declare-styleable name="IconView">
    <attr name="icon" format="enum">
        <enum name="enum_name_one" value="0"/>
        ....
        <enum name="enum_name_n" value="666"/>
   </attr>
</declare-styleable>

layout.xml

<com.xyz.views.IconView
    android:id="@+id/heart_icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:icon="enum_name_x"/>

我需要的是:mCustomView.setIcon(R.id.enum_name_x);但是我找不到枚举,或者我什至不知道如何获得枚举或枚举的名称.

What I need is something like: mCustomView.setIcon(R.id.enum_name_x);But I can not find the enum or I even have no idea how I can get the enum or the names of the enum.

推荐答案

似乎没有一种从属性枚举中获取 Java 枚举的自动化方法 - 在 Java 中您可以获取您指定的数值 - 字符串是用于 XML 文件(如您所示).

There does not seem to be an automated way to get a Java enum from an attribute enum - in Java you can get the numeric value you specified - the string is for use in XML files (as you show).

您可以在视图构造函数中执行此操作:

You could do this in your view constructor:

TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.IconView,
                0, 0);

    // Gets you the 'value' number - 0 or 666 in your example
    if (a.hasValue(R.styleable.IconView_icon)) {
        int value = a.getInt(R.styleable.IconView_icon, 0));
    }

    a.recycle();
}

如果要将值转换为枚举,则需要自己将值映射到 Java 枚举,例如:

If you want the value into an enum you would need to either map the value into a Java enum yourself, e.g.:

private enum Format {
    enum_name_one(0), enum_name_n(666);
    int id;

    Format(int id) {
        this.id = id;
    }

    static Format fromId(int id) {
        for (Format f : values()) {
            if (f.id == id) return f;
        }
        throw new IllegalArgumentException();
    }
}

然后在您可以使用的第一个代码块中:

Then in the first code block you could use:

Format format = Format.fromId(a.getInt(R.styleable.IconView_icon, 0)));

(虽然此时抛出异常可能不是一个好主意,可能最好选择一个合理的默认值)

(though throwing an exception at this point may not be a great idea, probably better to choose a sensible default value)

这篇关于如何在代码中获取在 attrs.xml 中创建的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 20:08