Reputation:
In my application I want show some text into TextView
, and I get this text from server.
I should use just one textView
in XML layout, and I should set color for this Texts.
My XML :
<TextView
android:id="@+id/rowExplore_userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/size3"
android:layout_marginTop="@dimen/padding8"
android:layout_toRightOf="@+id/rowExplore_imageCard"
android:fontFamily="sans-serif"
android:gravity="left|center_vertical"
android:text="Adam"
android:textColor="@color/colorPrimary"
android:textSize="@dimen/font14" />
JSON :
"name": "Adam Sandel",
"info": "liked",
"movieName": "SpiderMan",
Java code :
rowExplore_userName.setText(response.getName() + response.getInfo() + response.getMovieName() );
I want set color dynamically such as below image :
How can I it? Please help me
Upvotes: 1
Views: 2724
Reputation:
I would have another approach just create one method
public String getColoredString(String pname) {
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
Spannable wordToSpan = new SpannableString(pname);
wordToSpan.setSpan(new ForegroundColorSpan(color), 0, pname.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return wordToSpan.toString();
}
and use above method
rowExplore_userName.setText(getColoredString(response.getName())+getColoredString(response.getInfo())+getColoredString(response.getMovieName()));
this should work.
Upvotes: 0
Reputation: 6849
You can use SpannableString
if you want to avoid using HTML tags
TextView textview = (TextView)findViewById(R.id.textview);
Spannable wordToSpan = new SpannableString("Your text is here");
wordToSpan.setSpan(new ForegroundColorSpan(Color.BLUE), indexStart, indexEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(wordToSpan);
and it is more flexible since you can make more changes to your text (text size, bold/italic, etc)
Upvotes: 1
Reputation: 511
I used this code:
String colorStr="#FFFFFF" //put your hex color
int color = Color.parseColor(colorStr);
editText.setTextColor(color);
Upvotes: 1
Reputation: 2919
A better approach to this is to create a string resource with appropriate HTML tags:
<string name="html_string" formatted="false">
<![CDATA[
<font color="yellow">%s</font> %s <font color="yellow">%s</font>
]]>
</string>
And then get that string with resources:
String htmlString = getString(R.strings.html_string, response.getName(), response.getInfo(), response.getMovieName());
rowExplore_userName.setText(htmlString);
Upvotes: 1
Reputation: 474
You can use HTML
String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));
Upvotes: 3