在 Android Studio 中为 TextView 添加背景颜色



我正在尝试为Android studio中的两个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];
Random random = new Random( );
labelHeight = height ;
labelwidth = width / numberOfPieces;
for( int i = 0; i < tvs.length; i++ ) {
tvs[i] = new TextView( activity );
tvs[i].setGravity( Gravity.CENTER);
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] );
}
}

您可以使用setBackgroundResource来设置背景颜色。这是一个片段。

TextView textView = new TextView(activity);
textView.setBackgroundResource(R.color.red);

请参阅此官方文档

最新更新