【问题标题】:Android setError("error") not working in TextviewAndroid setError("error") 在 Textview 中不起作用
【发布时间】:2012-11-10 14:09:45
【问题描述】:

我们可以在 Edittext 中成功设置错误,但在 textview 中设置失败。有什么问题吗?? 我试过了

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

但我没有弹出错误消息。

【问题讨论】:

标签: android error-handling popup textview


【解决方案1】:

默认 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");

【讨论】:

  • 我更喜欢这个解决方案。将样式设置为@android:style/Widget.EditText 是多余的,并且会使 TextView 看起来像 EditText。
  • 这个解决方案比公认的答案干净得多。
  • 这是一个更好的解决方案,毫无疑问
  • 它会在点击 textview 时打开键盘
【解决方案2】:

实际上,您可以将 setError 用于 textView 并显示其弹出窗口。

您只需要使用与 EditText 相同的样式。

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

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

【讨论】:

  • nayoga0's answer 比这个好很多。
  • @DavidLord 以哪种方式?
  • 它弹出键盘:/
  • @AdeelTurk 很高兴你这样做了,但你能分享一下你是怎么做到的吗?它可以帮助社区,如果有问题,这里的人们可以使它没有错误。 :)
  • 嘿大家我当时很着急所以没时间解释,我采用了上面给出的相同解决方案,但是每当你在现场查看错误消息时,它会激活键盘,所以我把 android:focusableInTouchMode="true" android:focusable="true" 放在 textview 中效果很好。
【解决方案3】:

这是你唯一需要在 TextView 上获得预期的 setError 行为

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

【讨论】:

  • 简单到不行,并没有显示出令人讨厌的editText风格!
  • 但它也会在点击 textview 时打开键盘
【解决方案4】:

片段:你必须 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();
    }
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-02
    • 2016-09-22
    • 2016-02-22
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2017-01-14
    • 2014-07-19
    相关资源
    最近更新 更多