Android: set text color for programmatically created TextView

I created the program code TextView, now I want to set the text color to TextViewbelow, this is my code

TableLayout ll = (TableLayout) findViewById(R.id.auditContent);
public TableRow row;
TextView txtNumber;

for (int i = 0; i < ItemCount; i++) {
row = new TableRow(MainActivity.this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
                    row.setLayoutParams(lp);
                    row.setWeightSum(1f);
      txtNumber = new TextView(MainActivity.this);
      txtNumber.setGravity(Gravity.CENTER);
      txtNumber.setText("No." + count);
      txtNumber.setTextColor(getResources().getColor(R.color.blue)); //setting text color

 row.addView(txtNumber);

ll.addView(row, i);
    }

textcolordoesn’t set the color in the text TextView, t does something wrong, And I am debugging the code, there is no error. Please help thanks

In string.xml <color name="blue">#33CCCC</color> m not using color.xml The above color will work fine for xmlTextView

+4
source share
5 answers

According to your xml file you need to change

txtNumber.setTextColor(getResources().getColor(R.color.blue));

to

txtNumber.setTextColor(getResources().getString(R.color.blue));

Next, you can make a color.xmlfile in your folder valuesand use

<color name="mycolor">#33CCCC</color>

now just use this method

txtNumber.setTextColor(getResources().getColor(R.color.mycolor));
+12
source

Android Support Library 23

txtNumber.setTextColor(ContextCompat.getColor(context, R.color.your_color));
+5

USe

text.setTextColor(Color.rgb(200,0,0));
setTextColor(Color.parseColor("#FFFFFF"));
text.setTexColor(getResources().getColor()(R.color.colorname)

,

  #eaeaea

0

//

int color;

//in on create

color = Integer.parseInt("YOUR COLOR CODE", 16)+0xFF000000;
{
 txtNumber = new TextView(MainActivity.this);
 txtNumber.setGravity(Gravity.CENTER);
 txtNumber.setTextColor(color); //setting text color
}
0

Use this to change the text color:

textview.setTextColor(new Color().parseColor("#ffffff"));
-2
source

Source: https://habr.com/ru/post/1535900/


All Articles