2015-04-23 103 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); 
相關問題