Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set background for textview in code?

I set textview background equal transparent, and now I want change it's background in code. when click on mybtn (this is a button) change textview background, how do it?

code:

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();
   }
});
like image 552
Omid Nazifi Avatar asked Oct 17 '11 05:10

Omid Nazifi


People also ask

How do I add background color to TextView?

To change the background color of TextView widget, set the background attribute with required Color value. You can specify color in rgb , argb , rrggbb , or aarrggbb formats. The background color is applied along the width and height of the TextView.

How do I change text color in programmatically?

Android TextView – Text Color. TextView Text Color – To change the color of text in TextView, you can set the color in layout XML file using textColor attribute or change the color dynamically in Kotlin file using setTextColor() method.


2 Answers

Dont use setBackgroundDrawable but use::

@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();
   }
});

Make sure textview_logo are stay in drawable folder

for set background :

txt.setBackgroundColor(Color.RED);
like image 133
Nikunj Patel Avatar answered Oct 08 '22 03:10

Nikunj Patel


You can set any color using this:

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

or

txt.setBackgroundColor(Color.RED); // set default RED color as background color
like image 24
Hiral Vadodaria Avatar answered Oct 08 '22 02:10

Hiral Vadodaria