0

In AndroidStudio , I've made a list containing colors to select from using AlertDialog.builder. I stored the colors in charSequence like this CharSequence colors[] = new CharSequence[] {"Red1" , "Green1", "Blue1"}; so far so good. Now I've made a class object1 that has an enum Color defined like this

     public class Object1 {
          public enum Color {
            Red, Green, Blue
        }
          private Color selectedColor;
          public Object1 (Color color) {
          this.selectedColor = color;
          }
    }

I want that whenever a color is selected from the AlertDialog a new instance of Object1 will be created with color chosen from the AlertDialog. meaning I need a way to convert charSequence into matching Color element (enum) and passed to objecgt1 constructor. How can I do this? I need to convert "Green1" for example into Object1.Color.Green I don't this that the ValueOf method will help here since Green and Green1 are different Strings Thank you

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Noam
  • 1,640
  • 4
  • 26
  • 55

3 Answers3

2

You can do the following to get enum object from a given String.

public class Object1{

     public static enum Color {
        RED("Red1"), GREEN("Green1"), BLUE("Blue1");

        private String type;

        Color(String type) {
            this.type = type;
        }

        public String getType() {
            return type;
        }

        public static Color fromString(String text) {
            if (text != null) {
                for (Color color : Color.values()) {
                    if (text.equalsIgnoreCase(color.type)) {
                        return color;
                    }
                }
            }
            return null;
        }
    }
}

Now if you call

Object1.Color type = Object1.Color.fromString("Green1");

It will return you an enum of 'GREEN' type.

Thanks.

Md Sufi Khan
  • 1,751
  • 1
  • 14
  • 19
1

You only need to map the String values to the enum names. This can be done as easy as the following:

public static Color getColor(String name) {
    String mappedName = name.substring(0, name.length() - 1);
    return Color.valueOf(mappedName);
}

But it totally depends on your only logic, so just try to map it depending on your real implementation.

tynn
  • 38,113
  • 8
  • 108
  • 143
1

You will need to add something to translate your char sequences to Colors. I would recommend using a static map:

  private static Map<CharSequence, Color> charsToColors;
  static
  {
    charsToColors = new HashMap<>();
    charsToColors.put("Red1", Color.Red);
    charsToColors.put("Green1", Color.Blue);
    charsToColors.put("Blue1", Color.Green);
  }

Then when you need the Color for the CharSequence you could get it like so:

charsToColors.get("Red1")

As tynn said there are other ways to do this too, you just need to pick the one that best fits your use case.

Dr. Nitpick
  • 1,662
  • 1
  • 12
  • 16