Android中的TextView的setError("error")无法正常工作

33

我们成功地在EditText中设置了错误,但在TextView中设置错误失败了。有什么问题吗?我尝试过了。

((TextView) findViewById(R.id.df)).requestFocus();
((TextView) findViewById(R.id.df)).setSelected(true);
((TextView) findViewById(R.id.df)).setError("akjshbd");

但我没有收到错误的弹出窗口。

Textview Error


@Anis,这是在http://developer.android.com/reference/android/widget/TextView.html中写的,setError(CharSequence error):将TextView的右侧复合绘图设置为“错误”图标,并设置一个错误消息,当TextView具有焦点时将在弹出窗口中显示。 - MysticMagicϡ
4个回答

100

默认的TextView是不可获取焦点的。因此,您需要设置android:focusable="true"android:focusableInTouchMode="true"

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:text="@string/hello_world" />

无需设置setSelected(true)。

((TextView) findViewById(R.id.df)).requestFocus();
((TextView) findViewById(R.id.df)).setError("akjshbd");

7
我更喜欢这个解决方案。将样式设置为@android:style/Widget.EditText 过于复杂了,会使TextView看起来像一个EditText。 - starkej2
4
这个解决方案比被接受的答案更加简洁。 - Ridcully
1
这是一个更好的解决方案,毫无疑问。 - Gnzlt
点击TextView后,它会同时打开键盘。 - Adeel Turk

42

实际上,你可以对 textView 使用 setError 方法并显示其弹出窗口。

你只需要使用与 EditText 相同的样式即可。

只需在 xml 中为 textView 添加以下属性:

style="@android:style/Widget.EditText"

11
nayoga0的回答比这个好得多。 - David Lord
@DavidLord 以什么方式? - android developer
1
@AdeelTurk,很高兴你做到了,但你能分享一下你是如何做到的吗?这可能会对社区有所帮助,如果有任何问题,这里的人们可以使其无缝运行。 :) - Sufian
1
大家好,那时我很匆忙,所以没有时间解释。我采用了上面提供的相同解决方案,但每当你点击字段查看错误消息时,它会激活键盘,所以对我来说,在TextView中放置android:focusableInTouchMode="true"和android:focusable="true"就像魔法一样奏效。 - Adeel Turk
@androiddeveloper和Sufiyan,抱歉让你们久等了 #和平 ;) - Adeel Turk
显示剩余6条评论

14

这是唯一需要做的,以获得在TextView上预期的setError行为。

android:focusable="true"
android:clickable="true"
android:focusableInTouchMode="true"

1
足够简单,而且不显示那令人烦恼的editText样式! - Choletski
1
但是在TextView被点击时,它也会打开键盘。 - seema

5

片段:你需要调用requestFocus()方法来使视图显示错误信息。

    // Check for a valid email address.
if (TextUtils.isEmpty(mEmail)) {
    mEmailView.setError(getString(R.string.error_field_required));
    focusView = mEmailView;
    cancel = true;
} else if (!mEmail.contains("@")) {
    mEmailView.setError(getString(R.string.error_invalid_email));
    focusView = mEmailView;
    cancel = true;
}

if (cancel) {
    // There was an error; don't attempt login and focus the first
    // form field with an error.
    focusView.requestFocus();
} else {
    // Show a progress spinner, and kick off a background task to
    // perform the user login attempt.
    // showProgress(true);
    // mAuthTask = new UserLoginTask();
    // mAuthTask.execute((Void) null);
    ParseUser.logInInBackground(mEmail, mPassword, new LogInCallback() {

    @Override
    public void done(ParseUser user, ParseException e) {
        finishAndStartCardActivity();
    }
    });
}

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