4

1) Is it possible to set a TextView's color programmatically? If so what's the easiest way?

I want something else other that the default 4.0+ light-blue color.

I found and tried the following code without success:

StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed}, new ColorDrawable(0x1A000000));
states.addState(new int[] {android.R.attr.state_focused}, new ColorDrawable(0x1A000000));

if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    tv.setBackgroundDrawable(states);
} else {
    tv.setBackground(states);
}

I do not wish any XML involved.

2) Can I change the focus color in my themes in general? If yes how?

XML is obviously fine here.

Diolor
  • 13,181
  • 30
  • 111
  • 179

4 Answers4

10

You can use ColorStateList, to specify the state color programmatically.

    int[][] states = new int[][] {
        new int[] { android.R.attr.state_pressed}, // pressed
        new int[] { android.R.attr.state_focused}, // focused
        new int[] { android.R.attr.state_enabled} // enabled
    };

    int[] colors = new int[] {
        Color.parseColor("#008000"), // Green
        Color.parseColor("#0000FF"), // Blue
        Color.parseColor("#FF0000")  // Red
    };
    
    ColorStateList list = new ColorStateList(states, colors);
    textView.setTextColor(list);        
    textView.setClickable(true);
    textView.setFocusableInTouchMode(true);
Mr_Milky
  • 155
  • 9
Manish Mulimani
  • 17,535
  • 2
  • 41
  • 60
  • You are correct, this is the solution to the question. Although I wrote a wrong question (I wanted background color instead of text color). Here's the bounty. – Diolor May 31 '14 at 13:39
0

Create file res/drawable/text_color.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:color="#ffffff" />
    <item android:state_focused="true" android:state_pressed="true" android:color="#ffffff" />
    <item android:state_focused="false" android:state_pressed="true" android:color="#ffffff" />
    <item android:color="#000000" />
</selector>

Then use @drawable/text_color from xml (or R.drawable.text_color from code) as text color for your TextView.

Artyom Kiriliyk
  • 2,513
  • 1
  • 17
  • 21
  • 1
    in this case please use `setTextColor(getResources().getColorStateList(R.drawable.text_color));` – NikkyD Sep 09 '14 at 19:32
0

Do you mean how to set color if some event happents? If it is then you can set textView color as follow:

  textView.setTextColor("give color-code"); 
Mukesh
  • 266
  • 1
  • 4
  • 10
-1

You need to create style for that. By using style you can modify text color, background color, etc whatever you want.

laalto
  • 150,114
  • 66
  • 286
  • 303
Shrikant Salunkhe
  • 329
  • 1
  • 4
  • 14