如何在文本输入字段中添加星号

时间:2017-10-23 13:39:18

标签: java android xml android-layout

如何在条目中显示红色星号,以便您可以在文本末尾(或文本中的任何位置)显示它以表明它是必填字段?

示例:

  

输入您的姓名*

上面的星号是红色的。

3 个答案:

答案 0 :(得分:3)

 /**
 * For setting mandatory fields  symbol     *     * @param hintData     * @return
 */
public SpannableStringBuilder setMandatoryHintData(String hintData) {
    String simple = hintData;
    String colored = " *";
    SpannableStringBuilder builder = new SpannableStringBuilder();
    builder.append(simple);
    int start = builder.length();
    builder.append(colored);
    int end = builder.length();
    builder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorGrayLight_75)), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return builder;
}

使用可以使用带有Edittext的Above代码并以语法方式设置您的提示。无法在InputTextLayout上设置红色astrik。

答案 1 :(得分:0)

为此,您需要使用SpannableStringBuilder和ForegroundColorSpan。

另一种方式:

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

答案 2 :(得分:0)

将此扩展用于 AppCompatEditText。

fun AppCompatEditText.addAsteriskSign() {
  val colored = "*"
  val builder = SpannableStringBuilder()
  builder.append(this.hint)
  val start = builder.length
  builder.append(colored)
  val end = builder.length

  builder.setSpan(
       ForegroundColorSpan(Color.RED), start, end,
      Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
  )
  this.hint = builder

}