2015-04-23 33 views
1
Random myColor = new Random(); 
tv.setTextColor(Color.rgb(myColor.nextInt(255), myColor.nextInt(255), myColor.nextInt(255))); 

string.xml:如何在android中随机设置文字颜色?

<TextView 
      android:id="@+id/score" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Score" 
      android:textColor="@color/yellow" 
/> 

这将循环,我想每一个score文本有不同的颜色。但它不工作

+1

不要在这个问题的答案SO后帮你? http://stackoverflow.com/questions/5280367/android-generate-random-color-on-click – CubeJockey

+0

什么不工作? – Blackbelt

+5

不要这样做,如果它与背景颜色相同,将无法看到文字。而是制作一个预定义列表,并从列表中随机选择一个列表 –

回答

0

你必须让数字从0到255,所以产生了一种方法,为了得到这个数字来清洁您的代码:

private int getN() { 
    return (int) Math.random() * 255; 
} 

而设定的随机颜色的tv。 ..

tv.setTextColor(Color.rgb(getN(), getN(), getN())); 
0

使用Random

Random rand = new Random(); 
Color color = new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()); 

然后:

tv.setTextColor(color); 
相关问题