Fill ArrayList with colors for Android

后端 未结 5 597
夕颜
夕颜 2021-01-21 01:52

I want to create 2 ArrayList. One holding 16 colors, the other one holding 139.

I have the list with colors (both RGB as 255,126,32 and Hex as 0xFFFF2552). I want to use

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 02:22

    I would recommend against using a configuration file unless you want to be able to change your colors without code changes. I suspect your colors are constant though, so the file would just add unnecessary complexity to your application.

    The code sample in your question assumes java.awt.Color when you would actually use the utility class android.graphics.Color which cannot be instantiated.

    Therefore I recommend the following solution as a static variable (and be careful not to modify the contents of the array later):

    static final int[] colors16 = {
      Color.rgb(255, 0, 0),
      Color.rgb(0, 255, 0),
      Color.rgb(0, 0, 255)
    };
    

    Now add a static instance of Random to use for selecting random colors from the list.

    static final Random random = new Random();
    

    And then pick your color!

    int colorIndex = random.nextInt(colors16.size());
    Color color = colors16.get(colorIndex);
    

    If you feel it's important to protect the contents of your list, you can make it immutable as follows, at the small expense of boxing your color ints into Integer objects.

    static final List colors = Collections.unmodifiableList(
      Arrays.asList(
        Integer.valueOf(Color.rgb(255, 0, 0)),
        Integer.valueOf(Color.rgb(0, 255, 0)),
        Integer.valueOf(Color.rgb(0, 0, 255))
      )
    );
    

    Technically you can leave out the Integer.valueOf() conversion in the above snippet and Java will autobox the ints.

提交回复
热议问题