Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a red asterisk in a <string> entry

Tags:

android

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.

like image 443
charlest Avatar asked Jun 23 '11 15:06

charlest


2 Answers

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

like image 196
inazaruk Avatar answered Oct 25 '22 11:10

inazaruk


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);
like image 37
Ryan Avatar answered Oct 25 '22 12:10

Ryan