0

I have an android app that utilises a range of enums that will be seen by the user. rather than displaying the enum title (e.g. GRAMS) I want to be able to use the android strings.xml to handle this and have it handle multiple languages.

The problem is getting the reference to the strings file without having to getIdentifier (as suggested here)

Some code if it helps

Enum

public enum Mass implements Unit {
//SI
GRAMS,
KILOGRAMS}

strings.xml

<resources>
<string name="grams_name">grams</string>
<string name="grams_symbol">g</string>

3
  • You can add R.string.xxx to the enum itself as java enums are not like c,c++,... enums and can have custom properties Commented Mar 26, 2016 at 0:36
  • I considered that, but i would need to fill each enum with all the language options which is pretty messy. I was hoping there was a better way. Currently building a big switch statement in a handler to handle it in the mean time. Commented Mar 26, 2016 at 0:48
  • Ahhh, re read your comment. that is possible and should handle the language issue. I guess now its a toss up between making the project Units are stored in dependent on the android app, or my switch handler. Cheers Commented Mar 26, 2016 at 1:23

1 Answer 1

0

So the solution I implemented to solve this was to create a Handler method with a switch case that converts the Unit Enum, into a data object containing the display strings from the string.xml

public static UnitDisplayData getUnitDetails(Unit enum) {
 switch (enum.toString()) {
        // ---------ROOT UNITS----------
        case "GRAM":
            return new UnitDisplayData(
                    Mass.GRAM,
                    R.string.unit_grams_name,
                    R.string.unit_grams_symbol)
        ...
        }

While this does generate a load of boiler plate, this strategy works when dealing with multiple languages as android handles the strings.

It would also be possible to tie these resource references into the enum, but for my purposes I did not want my enum dependent on the app.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.