Saturday, April 17, 2021

How to use red * symbol on top of textview in Android

 I have a text view. Text view is mandatory so I want * symbol on top of text view in red color

How to use red * symbol on top of textview in Android

Answers 1 :

TextView text = (TextView)findViewById(R.id.text);

String simple = "Enter your name ";

String colored = "*";

SpannableStringBuilder builder = new SpannableStringBuilder(simple+colored);

builder.setSpan(new ForegroundColorSpan(Color.RED), simple.lenth(), builder.length(), 

            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

text.setText(builder);

You can use unicode for "ASTERISK" for that, this is upper version of "*", and use method above with spannable string.

TextView txt_name = (TextView) findViewById(R.id.text);

    String simple = "Name";

    String colored = "*";

    SpannableStringBuilder builder = new SpannableStringBuilder();

    builder.append(simple);

    int start = builder.length();

    builder.append(colored);

    int end = builder.length();

    builder.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    txt_name.setText(builder);

One of the easiest way to achieve this by using following code in your strings.xml file and provide color in your color.xml file

<string name="user_name">UserName <font color='red'>*</font></string>

No comments:

Post a Comment