Use an item as hint in Spinner (default item) and hide it in the dropdown

不羁的心 提交于 2020-01-05 05:28:28

问题


I am using the below code to select the last item of my list as hint of the spinner (ie. the default selected item in the spinner) and am trying to hide it from the dropdown menu.

List<String> rfpType = new ArrayList<>();
rfpType.add("Job");
rpType.add("Talent");  
rfpType.add("Vendor");
rfpType.add("Sponsor");
rfpType.add("RFP Title");

HintAdapter dataAdapter1 = new HintAdapter(getActivity(), android.R.layout.simple_list_item_1, rfpType);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerRFPType.setAdapter(dataAdapter1);
spinnerRFPType.setSelection(dataAdapter1.getCount());

HintAdapter

class HintAdapter extends ArrayAdapter<String>{

    public HintAdapter(Context context, int theLayoutResID , List<String> list){
        super(context, theLayoutResID, list);
    }

    @Override
    public int getCount() {
        // don't display last item. It is used as hint.
        int count = super.getCount();
        return count > 0 ? count-1 : count;
    }

}

But it displays the second last item as default. And hides the last item which I want to use as the hint. Suggest me a correct solution.


回答1:


Add this android:prompt="@string/country_prompt" to your spinner.

      <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/country_arrays"
        android:prompt="@string/country_prompt" />



回答2:


You need to implement below method in your adapter class:

It will help you:

Also for getCount return Count don't decrease it

 @Override
 public View getDropDownView(int position, View convertView,
        ViewGroup parent) 
 {
    LayoutInflater inflater = getLayoutInflater(null);
    convertView = inflater.inflate(theLayoutResID, parent,
            false);
    convertView= null;

    if(position == list.size() - 1)
    {
        holder.textView.setVisibility(View.GONE);
        convertView= holder;
    }
    else{
         convertView= super.getDropDownView(position, null, parent);
    }
    return convertView;

}


来源:https://stackoverflow.com/questions/38583105/use-an-item-as-hint-in-spinner-default-item-and-hide-it-in-the-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!