How can an error message be set for the Spinner in Android?

前端 未结 4 1014
借酒劲吻你
借酒劲吻你 2021-01-30 20:18

I\'d like to be able to call code like this, similar to how setError is set on a TextView:

spinner.setError(\"Error message\");

Ho

相关标签:
4条回答
  • 2021-01-30 20:57

    Here is a solution that uses a hidden TextView to get a pop-up message to appear, in addition to the error icon in the spinner. When in an error state, the Spinner looks like this:

    Spinner in invalid state

    When not in an error state, it looks like this.

    Spinner in valid state

    The complete solution is documented here: https://stackoverflow.com/a/29956372/3063884

    0 讨论(0)
  • 2021-01-30 21:02

    Spinner class will return a textview when you use getSelectedView(). So you can use setError() indirectly.

    ((TextView)spinner.getSelectedView()).setError("Error message");
    

    Results should be like ...

    setError in spinner

    Hope It will be helpful!

    0 讨论(0)
  • 2021-01-30 21:18

    There are a few solutions in this thread Creating a setError() for the Spinner:

    The EdmundYeung99's one works for me, either you are using your own adapter or not. Just put the following code in your validate function:

    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
    

    But, make sure you have at least one value in the Spinner adapter when you are doing your verification. If not, like an empty adapter waiting to be populate, make your adapter get an empty String:

    ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, new String[]{""});
    mySpinner.setAdapter(adapter);
    
    0 讨论(0)
  • 2021-01-30 21:24

    for people who are looking for a Kotlin answer

    val errorText = spinnerclient.selectedView as TextView
                    errorText.error = "client required"
                    errorText.requestFocus()
                    return@setOnClickListener
    

    The focus was returned but the text wasn't displayed. I will update once its displayed

    0 讨论(0)
提交回复
热议问题