Single Textview with Multiple Colored Text

Single TextView with multiple colored text

yes, if you format the String with html's font-color property then pass it to the method Html.fromHtml(your text here)

String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));

how can i create a textview with two color text?

You can use SpannableString to achieve the same.

TextView TV = (TextView)findViewById(R.id.textView);

Spannable wordtoSpan = new SpannableString("search in Sample Shop");

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 10, 21, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TV.setText(wordtoSpan);

Android multi color in one TextView

You can use Spannable to achieve what you want.

String text = "This is <font color='red'>red</font>. This is <font color='blue'>blue</font>.";

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE);
} else {
textView.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);
}

How can I change the color of a part of a TextView?

Spannable is more flexible:

String text2 = text + CepVizyon.getPhoneCode() + "\n\n"
+ getText(R.string.currentversion) + CepVizyon.getLicenseText();

Spannable spannable = new SpannableString(text2);

spannable.setSpan(new ForegroundColorSpan(Color.WHITE), text.length(), (text + CepVizyon.getPhoneCode()).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

myTextView.setText(spannable, TextView.BufferType.SPANNABLE);

Single textview with two different colors for dynamic text

Do this way..

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtHeader = (TextView) findViewById(R.id.txtHeader);
String str = "hello as new kkk @lll llll kkkk mm nn dd #jjj @pppp";

String[] str_array = str.split(" ");

for (int i = 0; i < str_array.length; i++) {
if (str_array[i].startsWith("@")) {
str=str.replaceAll(str_array[i], "<font color='red'>" + str_array[i] + "</font>");
} else if (str_array[i].startsWith("#")) {
str=str.replaceAll(str_array[i], "<font color='black'>" + str_array[i] + "</font>");
}
}

txtHeader.setText(Html.fromHtml(str));

}


Related Topics



Leave a reply



Submit