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));
相關文章
相關標籤/搜索