【问题标题】:How to add an asterisk in text input field如何在文本输入字段中添加星号
【发布时间】:2018-04-04 02:05:29
【问题描述】:

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

例子:

输入你的名字*

上面的星号是红色的。

【问题讨论】:

标签: java android xml android-layout


【解决方案1】:

将此扩展用于 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

}

【讨论】:

    【解决方案2】:
     /**
     * 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 一起使用,并以语法方式设置提示。无法在 InputTextLayout 上设置红色星号。

    【讨论】:

      【解决方案3】:

      为此,您需要使用 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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-03
        • 1970-01-01
        • 2015-08-09
        • 1970-01-01
        • 1970-01-01
        • 2021-05-10
        • 1970-01-01
        • 2012-11-09
        相关资源
        最近更新 更多