如何在代码中设置textview的背景?

Omi*_*ifi 4 android textview

我将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();
   }
});
Run Code Online (Sandbox Code Playgroud)

Nik*_*tel 18

不要使用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();
   }
});
Run Code Online (Sandbox Code Playgroud)

确保textview_logo留在drawable文件夹中

设置背景:

txt.setBackgroundColor(Color.RED);
Run Code Online (Sandbox Code Playgroud)


Hir*_*ral 9

你可以用这个设置任何颜色:

txt.setBackgroundColor(Color.parseColor("#BABABA")); // set any custom color as background color 
Run Code Online (Sandbox Code Playgroud)

要么

txt.setBackgroundColor(Color.RED); // set default RED color as background color
Run Code Online (Sandbox Code Playgroud)