Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Set textcolor for programmatically created TextView

I have created TextView programmatically, Now i want to set text color to the TextView below 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);
    }

The textcolor is not setting the color to TextView text, m doing anything wrong, And i debug 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 xml TextView

like image 596
W I Z A R D Avatar asked Apr 10 '14 09:04

W I Z A R D


People also ask

How do I change the color of my text messages on Android?

Open your device's Settings app . Text and display. Select Color correction. Turn on Use color correction.

How do I change text color in kotlin programmatically?

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

According to your xml file you need to change

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

to

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

Further more you can make color.xml file in your values folder and in that use

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

now just use this way

txtNumber.setTextColor(getResources().getColor(R.color.mycolor));
like image 60
Piyush Avatar answered Nov 15 '22 06:11

Piyush


Starting from Android Support Library 23

txtNumber.setTextColor(ContextCompat.getColor(context, R.color.your_color));
like image 33
Parth Vora Avatar answered Nov 15 '22 05:11

Parth Vora