Having the mandatory symbol to the edit text (red color asterisk) which is inside the textinputlayout

落花浮王杯 提交于 2019-12-04 15:23:01

Suppose you have EditTexts for mandatory values. You want the hint to be a red asterisk followed by the text in light grey.

After the EditTexts you have the explanation: TextView with red asterisk followed by text " = field is required"

In my case I used this this:

showEditTextsAsMandatory ( joinEmailET, joinNameET, passwordET, confirmPasswordET );
showTextViewsAsMandatory ( ( TextView ) findViewById ( R.id.requiredText ) );

public void showEditTextsAsMandatory ( EditText... ets )
{
    for ( EditText et : ets )
    {
        String hint = et.getHint ().toString ();

        et.setHint ( Html.fromHtml ( "<font color=\"#ff0000\">" + "* " + "</font>" + hint ) );
    }
}

public void showTextViewsAsMandatory ( TextView... tvs )
{
    for ( TextView tv : tvs )
    {
        String text = tv.getText ().toString ();

        tv.setText ( Html.fromHtml ( "<font color=\"#ff0000\">" + "* " + "</font>" + text ) );
    }
}

You can do this using a small trick , i.e you have to change layout_gravity when OnFocusChangeListener called in Java code. Example:

//Set OnFocusChangeListener for EditText
edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                //astriskText is Object of your textview contains * as text
                if (hasFocus) {
                    //if edittext has focus then move it to top
                    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) astriskText.getLayoutParams();
                    lp.gravity= Gravity.TOP;
                    astriskText.setLayoutParams(lp);
                } else if(edittext.getText().toString().length()==0){
                    //else check if edittext is empty then move it back to center
                    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) astriskText.getLayoutParams();
                    lp.gravity= Gravity.CENTER_VERTICAL;
                    astriskText.setLayoutParams(lp);
                }
            }
        });

Try joining your TextInputLayout hint with spanned postfix wrapped in html:

public void setRequired(boolean required) {

  componentField.setHint(
    TextUtils.concat(
      componentField.getHint(),
      Html.fromHtml(
        getContext().getString(
          R.string.required_asterisk))));
}

Asterisk code should be stored in android strings.xml for correct escaping:

<string name = "required_asterisk"><![CDATA[<font color=\'#cc0029\'>&nbsp*</font>]]></string>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!