如何使TextInputLayout提示为必填字段为红色星号

使用设计支持库中的TextInputLayout时,是否可以在提示红色时仅创建星号? 我已经看到关于整个提示样式的信息,但是这更复杂一点,因为只有*应该是红色的,而不是整个消息。

材料设计示例显示了这一点,但设计库似乎没有任何选择使用TextInputLayout和EditText以这种方式进行设计。

参考: https : //www.google.com/design/spec/components/text-fields.html#text-fields-required-fields

示例(带焦点的顶部有红色星号;没有焦点的底部没有红色星号):

带红色星号的提示文本示例

我研究了在OnFocusChangeListener中设置提示到一个SpannableString(请参阅这里如何获取一个<string>条目中的红色星号 )(请参阅这里有textinputlayout内的编辑文本(红色星号)的必需符号 ) ,但提示是一个CharSequence。

有没有办法做到这一点,而不扩展TextInputLayout?

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/black</item> </style> 

改变你的主题colorAccent,看看

是的可能的,因为我在我目前的应用程序做同样的事情。 为了重点和不重点,你必须做一些逻辑删除星号。

 String mm = "Legal first name"; Spannable WordtoSpan = new SpannableString(mm); WordtoSpan.setSpan( new ForegroundColorSpan(Color.parseColor("#e62e6c")), 16, mm.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); WordtoSpan.setSpan(new RelativeSizeSpan(0.9f), 16, mm.length(), 0); view.setText(WordtoSpan); 

我经历了同样的过程,并为我工作

  TextView text = (TextView) rootView.findViewById(R.id.name_textview); SpannableStringBuilder builder1 = setStarToLabel("Name"); text.setText(builder1); @NonNull private SpannableStringBuilder setStarToLabel(String text) { String simple = text; 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); return builder; } 

你可以添加一个跨越的字符串从Html?

  String grey = "Legal first name*"; Spanned redStar; String html = "<string style="color:grey;">Legal first name<span style="color:red;">*</span></string>"; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { redStar = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY); } else { redStar = Html.fromHtml(html); } 

并改变重点的提示。

  textInput.setOnFocusChangeListener(new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) myEditText.setHint(redStar.toString); else myEditText.setHint(grey); } 

通过添加包装在html中的后缀来更改TextInputLayout提示:

 public void setRequired(boolean required) { componentField.setHint( TextUtils.concat( componentField.getHint(), Html.fromHtml( getContext().getString( R.string.required_asterisk)))); } 

Asterisk代码应该存储在android strings.xml中以进行正确的转义:

 <string name = "required_asterisk"><![CDATA[<font color=\'#cc0029\'>&nbsp*</font>]]></string> 

截至09年9月9日,此页面上的材料设计指南没有红色的asterix,下面的图片显示了edittext聚焦和未聚焦的状态。

材料设计为作为提示文本一部分的必填字段指定一个星号,并为相同的颜色指定一个星号(不像您在问题中显示的那样是红色的)。

在Kotlin中,这非常简单:

1.定义这个扩展方法:

 fun TextInputLayout.markRequired() { hint = "$hint *" } 

2.使用它:

 input_first_name.markRequired()