Use an item as hint in Spinner (default item) and

2019-07-26 18:13发布

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.

2条回答
我命由我不由天
2楼-- · 2019-07-26 18:45

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" />
查看更多
Deceive 欺骗
3楼-- · 2019-07-26 19:02

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;

}
查看更多
登录 后发表回答