打印出彩色串[Android]

时间:2016-02-02 01:02:34

标签: android arrays string random colors

我在我的应用程序中随机生成颜色,并且我有来自XML的整数颜色数组:

<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<item name="blue" type="color">#FF33B5E5</item>
<item name="purple" type="color">#FFAA66CC</item>
<item name="green" type="color">#FF99CC00</item>
<item name="orange" type="color">#FFFFBB33</item>
<item name="red" type="color">#FFFF4444</item>
<item name="darkblue" type="color">#FF0099CC</item>
<item name="darkpurple" type="color">#FF9933CC</item>
<item name="darkgreen" type="color">#FF669900</item>
<item name="darkorange" type="color">#FFFF8800</item>
<item name="darkred" type="color">#FFCC0000</item>

<integer-array name="androidcolors">
    <item>@color/blue</item>
    <item>@color/purple</item>
    <item>@color/green</item>
    <item>@color/orange</item>
    <item>@color/red</item>
    <item>@color/darkblue</item>
    <item>@color/darkpurple</item>
    <item>@color/darkgreen</item>
    <item>@color/darkorange</item>
    <item>@color/darkred</item>
</integer-array>

代码是:

int[] androidColors = getResources().getIntArray(R.array.androidcolors);
    int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
    layout.setBackgroundColor(randomAndroidColor);
    //layout.addView(textView);
    TextView textView1 = new TextView(this);
    textView1.setTextSize(20);
    String message1 = new String(...);
    textView1.setText(message1);
    layout.addView(textView1);

我要把什么放在String构造函数中(其中有三个点),所以在message1对象中将设置为颜色的名称,这是生成整数变量randomAndroidColor ??

1 个答案:

答案 0 :(得分:1)

我看到问题的方法是你必须在int数组的项目中定义一个name属性,并使用XML解析器获取属性。但我不认为你想要获得预先定义的颜色名称会有那么多麻烦。

您可以简单地创建另一个字符串数组并获取名称

<integer-array name="androidcolors">
  <item>@color/blue</item>
  <item>@color/purple</item>
  <item>@color/green</item>
  <item>@color/orange</item>
  <item>@color/red</item>
  <item>@color/darkblue</item>
  <item>@color/darkpurple</item>
  <item>@color/darkgreen</item>
  <item>@color/darkorange</item>
  <item>@color/darkred</item>
</integer-array> 

<string-array name="colornames">
  <item>blue</item>
  <item>purple</item>
  <item>green</item>
  <item>orange</item>
  <item>red</item>
  <item>darkblue</item>
  <item>darkpurple</item>
  <item>darkgreen</item>
  <item>darkorange</item>
  <item>darkred</item>
</string-array>

现在您可以使用代码

访问颜色名称
int[] androidColors = getResources().getIntArray(R.array.androidcolors);
String [] androidColorsNames = getResources().getStringArray(R.array.colornames);

int randomNumber=new Random().nextInt(androidColors.length);

int randomAndroidColor = androidColors[randomNumber];
layout.setBackgroundColor(randomAndroidColor);
//layout.addView(textView);
TextView textView1 = new TextView(this);
textView1.setTextSize(20);
String message1 = androidColorsNames[randomNumber] ;
textView1.setText(message1);
layout.addView(textView1);

如果您还想使用XML解析器,请参阅this answer