java - 在 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);
参考这个官方文档
推荐阅读
- php - 如果使用准备好的语句,是否需要过滤/清理输入?
- node.js - 如何在频道中检查 Discord.js Bot 的权限?
- python - 按组对点进行指数拟合
- assembly - MARS 指令计数器是否适用于静态或动态指令?
- c# - C# Unity如何只选择数组中的一项并取消选择其他项
- phaser-framework - 如何隐藏播放器上的绿色边框?移相器
- node.js - 如何将数据从缓冲区转换为缓冲区?
- javascript - 验证只允许数字的文本框
- android - GoogleSignIn - 如何刷新访问令牌?在文档中找不到任何内容
- ansible - 嵌套字典列表中的ansible访问键