Android UI生成随机颜色

以 TextView 举个栗子,我知道的两种简单的方法:dom

第一种方法

利用 Color 类的 parseColor() 方法,这个方法传入的是颜色对应的代码,好比 #FFFFFF,因此要生成一个随机的这样的 String 对象就好了,代码:spa

TextView textView = (TextView)view.findViewById(R.id.textView);
String r,g,b;
Random random = new Random();
r = Integer.toHexString(random.nextInt(256)).toUpperCase();
g = Integer.toHexString(random.nextInt(256)).toUpperCase();
b = Integer.toHexString(random.nextInt(256)).toUpperCase();

r = r.length()==1 ? "0" + r : r ;
g = g.length()==1 ? "0" + g : g ;
b = b.length()==1 ? "0" + b : b ;
textview.setTextColor(Color.parseColor("#" + r + g + b);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

第二种方法

上面那个比较麻烦,下面这个跟这个一个原理。 
利用 Color 类的 rgb() 方法,传入三个 int(0~255) 数值,就是红绿蓝的值,代码:code

Random random = new Random();
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
textView.setTextColor(Color.rgb(r,g,b));
相关文章
相关标签/搜索