如何在<string>条目中获取红色星号

cha*_*est 11 android

如何在条目中获得红色星号,以便您可以在文本末尾显示它以指示其必填字段,例如:输入您的姓名*(星号将为红色).或者,就此而言,文本中的任何地方.

ina*_*ruk 37

您无法通过xml字符串资源执行此操作.这只能通过代码完成.为此你需要使用SpannableStringBuilderForegroundColorSpan.


这是一个小例子:

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);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 太棒了.Android平台非常方便. (2认同)