How to Set android:textColor using drawable in Android?
Asked Answered
G

6

14

I know how to set a drawable as the color of the text using xml but I don't know how it is done in Java.

In xml is something like this:

android:textColor="@drawable/selected_color"

in JAVA ?

Gillard answered 21/11, 2011 at 15:56 Comment(0)
C
2

Assuming that by "drawable" you mean a selector with color items, you should refer to this question.

You won't be able to use the textcolor with image drawables, or selectors containing image drawables.

Capability answered 21/11, 2011 at 16:2 Comment(0)
P
16

Assuming that by "drawable" you mean a selector with color items like this:

res/color/your_colors.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="#ffffffff"/>
    <item android:color="#ff1c5fab"/>
</selector>

You can use this code: mText.setTextColor(getResources().getColorStateList(R.color.your_colors));

Paddock answered 31/1, 2015 at 13:29 Comment(0)
S
5

color/selector_colors.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color="@color/white" android:state_checked="true" />
    <item android:color="@color/white" android:state_pressed="true" />
    <item android:color="@color/white" android:state_activated="true" />

    <item android:color="@color/black" />

</selector>

you have to implement it into textview like that:

textview.setTextColor(context.getResources().getColorStateList(R.color.selector_colors));
Sidnee answered 12/6, 2017 at 7:12 Comment(0)
C
2

Assuming that by "drawable" you mean a selector with color items, you should refer to this question.

You won't be able to use the textcolor with image drawables, or selectors containing image drawables.

Capability answered 21/11, 2011 at 16:2 Comment(0)
S
1

Did you see this, this, or this ?

The last link says to use:

tvImagesTitle.setTextColor( getResources().getColor(R.color.blue) ); 
Susannahsusanne answered 21/11, 2011 at 16:2 Comment(0)
P
0

One easy way is to use HTML:

StringBuilder text = new StringBuilder();
text.append("<font color='").append(selectedColor).append("'>")                     .append("your text here").append("</font>");

textView.setText(Html.fromHtml(text.toString()), BufferType.SPANNABLE);
Pythagoreanism answered 21/11, 2011 at 16:2 Comment(0)
P
0

res/color/selector_colors.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="#ffffffff"/>
    <item android:color="#ff1c5fab"/>
</selector>

You can directly use this code:

<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/selector_colors"
android:text="click" />
Prankster answered 12/1 at 6:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.