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

后端 未结 5 1848
小蘑菇
小蘑菇 2020-12-23 20:30

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

5条回答
  •  抹茶落季
    2020-12-23 20:34

    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)

提交回复
热议问题