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);
}
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