以 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);
上面那個比較麻煩,下面這個跟這個一個原理。
利用 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));