Android UI生成随机颜色
以 TextView 举个栗子,我知道的两种简单的方法:
第一种方法
利用 Color 类的 parseColor() 方法,这个方法传入的是颜色对应的代码,比如 #FFFFFF,所以要生成一个随机的这样的 String 对象就行了,代码:
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);
第二种方法
上面那个比较麻烦,下面这个跟这个一个原理。
利用 Color 类的 rgb() 方法,传入三个 int(0~255) 数值,就是红绿蓝的值,代码:
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));