Android Studio中为TextView设置指定背景颜色的技术问题
解决TextView固定背景颜色的问题
嘿,我明白你现在的需求——要把两个TextView分别设为红色和蓝色,而不是当前的随机颜色。咱们直接修改现有代码就行,很简单!
核心改动思路
现有代码里用Random生成了随机RGB值,咱们只需要在循环里根据索引判断,给第一个TextView设红色,第二个设蓝色就好。如果后续还有更多TextView,也可以灵活调整(比如其他的保持随机或者设默认色)。
修改后的完整代码
public void buildGuiByCode( Activity activity, int width, int height, int numberOfPieces ) { positions = new int[numberOfPieces]; tvs = new TextView[numberOfPieces]; colors = new int[tvs.length]; params = new LayoutParams[tvs.length]; // 不需要随机生成器了,除非你还要给其他TextView用随机色 labelHeight = height ; labelwidth = width / numberOfPieces; for( int i = 0; i < tvs.length; i++ ) { tvs[i] = new TextView( activity ); tvs[i].setGravity( Gravity.CENTER); // 根据索引设置固定颜色 if(i == 0){ // 第一个TextView设红色,用系统自带的Color.RED更方便 colors[i] = Color.RED; } else if(i == 1){ // 第二个TextView设蓝色 colors[i] = Color.BLUE; } // 如果还有更多TextView,可以在这里加else逻辑,比如继续用随机色或者设默认色 // else { // Random random = new Random(); // colors[i] = Color.rgb( random.nextInt(255 ), random.nextInt(255 ), random.nextInt(255 ) ); // } tvs[i].setBackgroundColor( colors[i] ); params[i] = new LayoutParams( labelwidth, height ); params[i].topMargin = 0; params[i].leftMargin = labelwidth * i; addView( tvs[i], params[i] ); } }
额外说明
- 我用了Android系统自带的
Color.RED和Color.BLUE,这些是预定义的常量,比手动写Color.rgb(255,0,0)更简洁易读。 - 如果你的
numberOfPieces大于2,想要其他TextView保持随机颜色,可以把注释里的else逻辑打开,这样前两个是固定色,后面的还是随机色。 - 记得确保
numberOfPieces的值是2(或者至少不小于2),不然第二个蓝色的TextView不会被创建哦。
内容的提问来源于stack exchange,提问作者Charlie Batista
相关产品推荐
相关产品推荐

