EditText.setError不显示错误文本,只显示图标。

3
我在我的应用中有一个简单的验证,我使用了四个EditText。当EditText失去焦点时,我会显示错误,但问题是失去焦点后,EditText只显示图标而不显示错误消息。我尝试使用requestFocus()方法,现在可以看到错误了,但问题是...现在我的表单显示两个光标,即使第一个字段无效并显示错误,我输入的任何内容都会进入第二个EditText。有谁能帮我解决这个问题吗? 谢谢。
这是我的xml文件-
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:hint="first name"
android:id="@+id/edt_first_name"/>

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="last name"
    android:id="@+id/edt_last_name"
    android:singleLine="true"
    android:layout_below="@+id/edt_first_name"/>
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="email"
    android:singleLine="true"
    android:id="@+id/edt_email"
    android:layout_below="@+id/edt_last_name"/>

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="password"
    android:singleLine="true"
    android:imeOptions="actionNext"
    android:id="@+id/edt_password"
    android:layout_below="@+id/edt_email"/>

这是我的主文件,我正在检查验证

firstname.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        public void onFocusChange(View v, boolean hasFocus) {

            if (!hasFocus) {
                if (!Validate(firstname.getText().toString())) {

                } else {
                    firstname.setFocusable(true);
                    firstname.setError("not valid");
                }
            }else{
                firstname.setError(null);
            }

        }
    });
1个回答

2

使用TextInputLayout可以像这样实现材料设计的EditText

<android.support.design.widget.TextInputLayout
            android:id="@+id/input_application_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="30dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:minHeight="50dp"
            android:theme="@style/MyTextInputLayout"
            app:hintTextAppearance="@style/TextAppearance.App.TextInputLayout">

            <EditText
                android:id="@+id/application_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/hint_application_name"
                android:imeOptions="actionNext"
                android:inputType="text" />

        </android.support.design.widget.TextInputLayout>

在您的Activity

TextInputLayout til = (TextInputLayout) findViewById(R.id.input_application_name);
EditText applicationNameEdt = (EditText) findViewById(R.id.application_name);
til.setErrorEnabled(true);
til.setError("You need to enter a name");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接