Android setError("错误")无法在Textview中运行

Bha*_*ara 29 error-handling android popup textview

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

((TextView) findViewById(R.id.df)).requestFocus();
((TextView) findViewById(R.id.df)).setSelected(true);
((TextView) findViewById(R.id.df)).setError("akjshbd");
Run Code Online (Sandbox Code Playgroud)

但我没有弹出错误.

Textview错误

nag*_*ya0 93

默认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" />
Run Code Online (Sandbox Code Playgroud)

而且无需设置setSelected(true).

((TextView) findViewById(R.id.df)).requestFocus();
((TextView) findViewById(R.id.df)).setError("akjshbd");
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢这个解决方案 将样式设置为@android:style/Widget.EditText是过度的,使TextView看起来像EditText. (6认同)
  • 这个解决方案比接受的答案更清晰. (4认同)

and*_*per 35

实际上,您可以对textView使用setError并显示其弹出窗口.

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

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

style="@android:style/Widget.EditText"
Run Code Online (Sandbox Code Playgroud)

  • [nayoga0的回答](http://stackoverflow.com/a/15954372/2209946)比这要好得多. (11认同)

ces*_*rds 12

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

android:focusable="true"
android:clickable="true"
android:focusableInTouchMode="true"
Run Code Online (Sandbox Code Playgroud)


Phi*_*vid 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();
    }
    });
}
Run Code Online (Sandbox Code Playgroud)