11

How do you get a red asterisk in a entry so that you can display it at the end of the text to indicate its a required field, like: Enter your name * (asterisk will be red). Or, for that matter, anywhere within the text.

charlest
  • 925
  • 2
  • 10
  • 20

5 Answers5

37

You can't do that through xml string resources. This can only be done via code. For this you need to use SpannableStringBuilder and ForegroundColorSpan.


Here is small example:

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

String simple = "Enter your 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);

text.setText(builder);

enter image description here

inazaruk
  • 74,247
  • 24
  • 188
  • 156
  • This worked exactly as needed: thanks! A related question with the Stack Overflow process in general: I was only able to increase the point count from 1 to 2 for the answer: do you have to have a certain privilege in order to award more than just a few points? – charlest Jun 23 '11 at 21:12
  • No, nobody can award more then one point per question/answer. Treat it like voting: you either vote for it, or against it. If you have question regarding how stackoverflow works, visit meta: http://meta.stackoverflow.com/; – inazaruk Jun 23 '11 at 21:33
  • How did you add that extra space though? I am assuming you didn't use `" *"` as string. – Yar Feb 02 '17 at 21:39
4

Refer to this for examples on how to style portions of a textview. Here's how you could do it for a red asterisk.

EditText editTxt = new EditText(this);
editTxt.setText("Testing asterisk *");
Spannable str = editTxt.getTxt();
int loc = editTxt.getTxt().toString().indexOf("*");
str.setSpan(new ForegroundColorSpan(Color.RED), loc, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
inazaruk
  • 74,247
  • 24
  • 188
  • 156
Ryan
  • 1,797
  • 12
  • 19
1

Alternative for showing asterisk in android Textview

txtvw2.setText(Html.fromHtml("<sup>*</sup>"+"enter you name"));
chetan mekha
  • 665
  • 6
  • 18
0

Initialize variable in strings.xml <string name="date_of_incident">Date of Incident <p><font color="red">*</font></p></string>

0

Write into strings.xml file

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

this helped me solve this problem.

Haoyu Guo
  • 11
  • 6