I have an Android Spinner view in my layout. I would like that spinner to show only a single text item when closed, but when the user clicks on it (i.e. opens the spinner di
Using the code of the tutorial linked by Flo, I created the following CustomSpinnerAdapter in order to show two different sets of strings, one when the items are displayed, and one when not. I hope it helps someone.
public class CustomSpinnerAdapter extends ArrayAdapter {
Context mContext;
int mTextViewResourceId;
String[] mObjects;
String[] mShortNameObjects;
public CustomSpinnerAdapter(Context context, int textViewResourceId,
String[] objects, String[] shortNameObjects) {
super(context, textViewResourceId, objects);
mContext = context;
mTextViewResourceId = textViewResourceId;
mObjects = objects;
mShortNameObjects = shortNameObjects;
}
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TextView row = (TextView) inflater.inflate(mTextViewResourceId, parent, false);
row.setText(mObjects[position]);
return row;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TextView row = (TextView) inflater.inflate(mTextViewResourceId, parent, false);
row.setText(mShortNameObjects[position]);
return row;
}
}
And the usage inside a Fragment:
CustomSpinnerAdapter mSpinnerAdapter = new CustomSpinnerAdapter(getActivity(), R.layout.spinner_item, getResources().getStringArray(R.array.action_filter), getResources().getStringArray(R.array.action_filter_short_names));
Finally, the layout for the spinner item:
spinner_item.xml