android - 如何设置动态创建的Textview的背景颜色?
问题描述
我在 android 中创建动态文本视图。视图已创建,但是当我单击 textview 时,我想在 android 中设置该特定 textview 的背景颜色。我已经尝试过,但它将颜色设置为仅最后一个文本视图而不是选定的文本视图。
这是我的代码
public class Demo extends AppCompatActivity implements View.OnClickListener {
private LinearLayout llOptions;
private TextView textView, tvOptionFirstQue;
private ArrayList<String> arrayList = new ArrayList<>();
private static final int MY_BUTTON = 9000;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_quiz_demo);
llOptions = findViewById(R.id.llOptions);
tvOptionFirstQue = findViewById(R.id.tvOptionFirstQue);
for (int i = 0; i < 4; i++) {
textView = new TextView(Demo
.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
float left = getResources().getDimension(R.dimen.common_twentyfive);
float top = getResources().getDimension(R.dimen.common_five);
float toppadding = getResources().getDimension(R.dimen.common_twelve);
float right = getResources().getDimension(R.dimen.common_twentyfive);
params.setMargins((int) left, (int) top, (int) right, 0);
textView.setPadding(0, (int) toppadding, 0, (int) toppadding);
textView.setTextSize(14);
textView.setBackgroundResource(R.drawable.button_background_light_gray);
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.BLACK);
textView.setId(i);
textView.setLayoutParams(params);
textView.setText("test" + i);
textView.setOnClickListener(this);
arrayList.add(textView.getText().toString());
this.llOptions.addView(textView);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case 0:
View child = llOptions.getChildAt(v.getId());
TextView textView1 = (TextView) child;
onFirstOptionClisk(textView1);
}
}
private void onFirstOptionClisk(TextView textView) {
textView.setBackgroundResource(R.drawable.rounded_lightblue_answer_backgroun);
textView.setTextColor(getResources().getColor(R.color.white));
}
解决方案
利用
textView.setBackgroundColor(Color.parseColor("#00ff00"));
反而
textView.setBackgroundResource(R.drawable.button_background_light_gray)
将工作
推荐阅读
- python - 在python中,有没有办法删除分隔符的最后一个实例之后的所有文本?
- azure-data-factory - 如何在通过管道从 CSV 文件映射数据流派生列中传递列模式匹配的数组?
- getstream-io - 在没有更新消息的情况下更新聊天频道?
- typescript - 打字稿通用约束
- python - 为熊猫数据框列应用条件
- git - 发布定义中的多个存储库
- html - 缓存控制标头可以有多个值吗?
- android - 我需要添加图像而无意发送电子邮件
- macos - 如何从可恢复的 NSWindow 中排除某些 AppKit 视图?
- selenium - 如何减少scrapy在蜘蛛上运行爬网时产生的selenium webdriver实例的数量?