How to get an enum which is created in attrs.xml in code

android custom view default attributes
declare-styleable
android attr
attrs in xml
xml enum
android custom view attributes programmatically
python-attrs enum
kotlin enum

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"/>

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.


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

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)

How to get an enum which is created in attrs.xml in code, 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. Examples. The following example applies the XmlEnumAttribute to the members of an enumeration. When the XmlSerializer generates XML data for this enumeration, the data conforms to the values of the Name properties.


It's simple let's show everybody an example just to show how easy it is:

attr.xml:

<declare-styleable name="MyMotionLayout">
    <attr name="motionOrientation" format="enum">
        <enum name="RIGHT_TO_LEFT" value="0"/>
        <enum name="LEFT_TO_RIGHT" value="1"/>
        <enum name="TOP_TO_BOTTOM" value="2"/>
        <enum name="BOTTOM_TO_TOP" value="3"/>
    </attr>
</declare-styleable>

Custom layout:

public enum Direction {RIGHT_TO_LEFT, LEFT_TO_RIGHT, TOP_TO_BOTTOM, BOTTOM_TO_TOP}
Direction direction;
...
    TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.MyMotionLayout);
    Direction direction = Direction.values()[ta.getInt(R.styleable.MyMotionLayout_motionOrientation,0)];

now use direction like any other enumeration variable.

core/res/res/values/attrs.xml - platform/frameworks/base, These are the standard attributes that make up a complete theme. -->. <declare-​styleable then in code manually set your window's background to. null so it will not be drawn. <enum name="wrap_content" value="0" />. </attr>. <! this flag is specified the IME may <em>not</em> be set up to be able. to display text, so it​  How to get an enum which is created in attrs.xml in code (2) I know it's been a while since the question was posted, but I had the same issue recently. I hacked a little something together that uses Square's JavaPoet and some stuff in the build.gradle that automatically creates a Java enum class from the attrs.xml on project build.


Well for sanity's sake. Make sure your ordinals are the same in your declared styleable as in your Enum declaration and access it as an array.

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

int ordinal = a.getInt(R.styleable.IconView_icon, 0);

if (ordinal >= 0 && ordinal < MyEnum.values().length) {
      enumValue = MyEnum.values()[ordinal];
}

sdk/platforms/android-21/data/res/values/attrs.xml , These are the standard attributes that make up a complete theme. -->. <declare-​styleable then in code manually set your window's background to. null so it will not be drawn. <enum name="aboveThumb" value="2" />. </attr>. <! this flag is specified the IME may <em>not</em> be set up to be able. to display text, so it​  attrsfile is where the XML with the declared styleable enums are. As you can see I've hardcoded a large chunk of the path as I don't know any other way to get it. def attrEnumTask = tasks.create("attrenum${variant.name}") << { This creates a new task. The ${variant.name} makes the task name unique per build variant otherwise you'll get complaints.


I know it's been a while since the question was posted, but I had the same issue recently. I hacked a little something together that uses Square's JavaPoet and some stuff in the build.gradle that automatically creates a Java enum class from the attrs.xml on project build.

There's a little demo and a readme with an explanation at https://github.com/afterecho/create_enum_from_xml

Hope it helps.

Creating a View Class, Android example source code file: attrs.xml (default, defines, if, preference, the, this) These are the standard attributes that make up a complete theme. <attr name="typeface"> <enum name="normal" value="0" /> <enum name="sans" typically you set this using the <code>@+ syntax to create a new ID resources. Working with enums in Java 10 you have many options of creating and using enums. Which one to use depends on your needs: * create simple enum and get ordinal * create enum with code field (instance field) * access values by FOR loop * Iterate with EnumSet and forEach * Iterate enum with Stream * All examples and filter enum values More info on enums from Java docs: * Class Enum [https://docs


Let me add a solution written in kotlin. Add inline extension function:

inline fun <reified T : Enum<T>> TypedArray.getEnum(index: Int, default: T) =
    getInt(index, -1).let { if (it >= 0) enumValues<T>()[it] else default 
}

Now getting enum is simple:

val a: TypedArray = obtainStyledAttributes(...)
val yourEnum: YourEnum = a.getEnum(R.styleable.YourView_someAttr, YourEnum.DEFAULT)
a.recycle()

Android example source code file (attrs.xml), These are the standard attributes that make up a complete theme. -->. <declare-​styleable <enum name="monospace" value="3" />. </attr>. <! this flag is specified the IME may <em>not</em> be set up to be able. to display text, so Use <code>input-method</code> as the root tag of the XML resource that. describes an. Public Class GetValuesTest Enum Colors Red Green Blue Yellow End Enum 'Colors Enum Styles Plaid = 0 Striped = 23 Tartan = 65 Corduroy = 78 End Enum 'Styles Public Shared Sub Main() Console.WriteLine("The values of the Colors Enum are:") Dim i As Integer For Each i In [Enum].GetValues(GetType(Colors)) Console.WriteLine(i) Next Console.WriteLine


core/res/res/values/attrs.xml - frameworks_base, The custom attribute definition in the attrs.xml will create a resource reference string color dimension boolean integer float fraction enum flag Also, if you are able to get access to the source code of Core Android jar you  C# Enumerations Type - Enum. In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer values. It makes constant values more readable, for example, WeekDays.Monday is more readable then number 0 when referring to the day in a week.


Understanding Android Custom Attributes: An Article, It's customary to put these resources into a res/values/attrs.xml file. popular code editors depend on this naming convention to provide statement completion. When a view is created from an XML layout, all of the attributes in the XML tag are read This method passes back a TypedArray array of values that have already  There is also a private constructor where we assign the passed value to a variable. This is done automatically upon using an enum due to the parenthesis after each enum name. Getting Enum from Integer. To get the enum for a given integer, we simply have to call the valueOf method, like below.


Lennken Test, Enumerations, in a form of enum class declarations, got a bad rep on The barbarian approach to create namespaces is using prefixes. data class ErrorResponse(@SerializedName("code") val code: String) It is possible to define enum in XML which is helpful with custom View Back val icon = attrs. In this example, we declared two enum variables s1 and s2.Here, we are declaring and assigning values to the variables at the same time. We are assigning values to the variables by two ways in this example. enum Season s1 = Spring; - This statement is assigning the value of Spring i.e. 1 to s1. enum Season s2(Winter); - This is the second way you can assign the value at the time of declaration.