Android Spinner with different layouts for “drop down state” and “closed state”?

前端 未结 6 2084
迷失自我
迷失自我 2020-11-29 01:42

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

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 02:06

    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

    
    
    

提交回复
热议问题