如何在代码中为TextView设置背景?

6

我将textview的背景设置为透明,并且现在想在代码中更改它的背景。 当点击mybtn(这是一个按钮)时更改textview的背景,如何实现?

代码:

Button btn = (Button) findViewById(R.id.btn_dialog);
btn.setBackgroundColor(color.transparent);
btn.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    TextView txt = (TextView) findViewById(R.id.txt);
    txt.setBackgroundColor(??????);

    Toast.makeText(getBaseContext(), "this test is ok!", Toast.LENGTH_SHORT).show();
   }
});
5个回答

20

不要使用 setBackgroundDrawable,而应该使用:

@Override
   public void onClick(View v) {
    TextView txt = (TextView) findViewById(R.id.txt);
    txt.setBackgroundResource(R.drawable.textview_logo);

    Toast.makeText(getBaseContext(), "this test is ok!", Toast.LENGTH_SHORT).show();
   }
});

请确保 textview_logo 存放在 drawable 文件夹中。

设置背景的代码:

txt.setBackgroundColor(Color.RED);

对不起,我要编辑我的代码,因为我想为我的TextView设置背景颜色,请帮帮我。 - Omid Nazifi

12

您可以使用以下方法设置任意颜色:

txt.setBackgroundColor(Color.parseColor("#BABABA")); // set any custom color as background color 
或者
txt.setBackgroundColor(Color.RED); // set default RED color as background color

1

有三种方法可以设置背景。

txt.setBackgroundResource(int rsid);
txt.setBakgroundDrawable(Drawable object);
txt.setBackgroundColor(color id);

最合适的是 txt.setBackgroundResource(int rsid);您可以直接从drawable文件夹中设置以下图像:
txt.setBakgroundResource(R.drawable.image_name);

0
如果您需要通过颜色进行识别,您应该使用以下代码:

txt.setBackgroundColor(R.color.someColorInColorsXML);

或者

txt.setBackgroundDrawable(new ColorDrawable(AARRGGBB));

0

在API 23之后,我认为最佳实践是使用:

setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.my_color));

这也应该确保向后兼容性得以维持(我自己没有测试过)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接