简体   繁体   中英

how to set text color randomly in android?

Random myColor = new Random();
tv.setTextColor(Color.rgb(myColor.nextInt(255), myColor.nextInt(255), myColor.nextInt(255)));

string.xml:

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

This will loop, I want every score text has different color. But its not working

You have to get numbers from 0 to 255, so generate a method to get this numbers in order to clean your code:

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

And the set the randomized color to your tv ...

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

Use Random :

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

Then:

tv.setTextColor(color);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM