Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a setError() for the Spinner

How do you create the setError() (similar to that of a TextView/EditText) function for a Spinner? The following doesn't work:

I tried extending the Spinner class and in the constructor:

ArrayAdapter<String> aa = new ArrayAdapter<String>(getContext(),                     android.R.layout.simple_spinner_item, android.R.id.text1,                     items);             aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);             setAdapter(aa);              tv = (TextView) findViewById(android.R.id.text1);             // types_layout_list_tv              ctv = (CheckedTextView) aa.getDropDownView(1, null, null);             tv2 = (TextView) aa.getView(1, null, null); 

setError method:

    public void setError(String str) {         if (tv != null)             tv.setError(str);         if(tv2!=null)             tv2.setError(str);         if (ctv != null)             ctv.setError(str);     } 
like image 359
Sameer Segal Avatar asked Sep 20 '10 09:09

Sameer Segal


People also ask

How to set setError in spinner Android?

Seterror method is not available for spinner.. u have to create other function or toast message to show it.


2 Answers

Similar to @Gábor's solution, but I didn't need to create my own adapter. I just call the following code in my validate function (i.e. on submit button clicked)

        TextView errorText = (TextView)mySpinner.getSelectedView();                           errorText.setError("anything here, just to add the icon");         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 
like image 72
EdmundYeung99 Avatar answered Oct 21 '22 00:10

EdmundYeung99


I have a solution that doesn't involve creating an extra edit field but you need your own SpinnerAdapter, as usual.

Make sure you have at least one TextView in the layout you use in your adapter's getView() (you normally have that, anyway).

Add the following function to your adapter (change name to the ID of your TextView):

public void setError(View v, CharSequence s) {   TextView name = (TextView) v.findViewById(R.id.name);   name.setError(s); } 

Call the setError() from your code this way:

YourAdapter adapter = (YourAdapter)spinner.getAdapter(); View view = spinner.getSelectedView(); adapter.setError(view, getActivity().getString(R.string.error_message)); 

Basically, as with any other control, only that you call it on your adapter and you have to provide the view as well.

This will display the error icon on the spinner as it is the case with other controls.

like image 44
Gábor Avatar answered Oct 20 '22 23:10

Gábor