如何获取在代码中的attrs.xml中创建的枚举 [英] How to get an enum which is created in attrs.xml in code

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

问题描述

我创建了一个自定义视图(发现它 here )与声明风格的属性类型枚举。在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.xxx.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();
}

如果要将该值设置为枚举,您需要将值映射例如:

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();
    }
}

然后在第一个代码块中,您可以使用: / p>

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中创建的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆