如何在Android中为Spinner设置错误消息?

Gop*_*h S 41 android spinner android-widget

我希望能够像这样调用代码,类似于setError在TextView上设置的方式:

spinner.setError("Error message");
Run Code Online (Sandbox Code Playgroud)

但是,setError仅适用于EditText,而不适用于Spinner.

我想通知用户是否未选择微调器字段.如何在不使用Toast的情况下执行此类通知?

Lio*_* T. 69

这个线程中有一些解决方案为Spinner创建一个setError():

EdmundYeung99的一个作品,对我来说,无论您使用的是自己的适配器或没有.只需将以下代码放入验证函数中:

TextView errorText = (TextView)mySpinner.getSelectedView();
errorText.setError("");
errorText.setTextColor(Color.RED);//just to highlight that this is an error
errorText.setText("my actual error text");//changes the selected item text to this
Run Code Online (Sandbox Code Playgroud)

但是,在进行验证时,请确保Spinner适配器中至少有一个值.如果没有,就像一个空的适配器等待填充,让你的适配器得到一个空字符串:

ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, new String[]{""});
mySpinner.setAdapter(adapter);
Run Code Online (Sandbox Code Playgroud)


Kha*_*han 32

使用时,Spinner类将返回textview getSelectedView().所以你可以setError()间接使用.

((TextView)spinner.getSelectedView()).setError("Error message");
Run Code Online (Sandbox Code Playgroud)

结果应该像......

spinner中的setError

希望它会有所帮助!

  • 非常好的想法,但如果没有选择项目就会中断,在这种情况下它会返回null. (2认同)