具有空默认选定项目的微调器

use*_*667 9 java android android-spinner

我正在尝试使用默认的空选定项创建一个微调器,但它显示了微调器选项中的第一个项.如果我将空值添加到我的字符串(这是spinner中的选择源),则在打开微调器后显示空行.我该怎么办?这是我正在使用的代码:

  String[] ch = {"Session1", "Session2", "Session3"};
  Spinner sp = (Spinner)findViewById(R.id.spinner1);
  TextView sess_name = findViewById(R.id.sessname);
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ch);
  sp.setAdapter(adapter);

  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

  sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener({
      @Override
      public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
          int index = arg0.getSelectedItemPosition();
          sess_name.setText(ch[index]);

          Toast.makeText(getBaseContext(), "You have selected item : " + ch[index], Toast.LENGTH_SHORT).show();
      }
Run Code Online (Sandbox Code Playgroud)

Jia*_* Qi 14

巴拉克的解决方案有问题.当您选择第一个项目时,Spinner将不会调用OnItemSelectedListener onItemSelected()并刷新空内容,因为前一个位置和选择位置都为0.

首先在字符串数组的开头放一个空字符串:

String[] test = {" ", "one", "two", "three"};
Run Code Online (Sandbox Code Playgroud)

第二个构建适配器,不要修改getView(),修改getDropDownView().将空视图的高度设置为1px.

public class MyArrayAdapter extends ArrayAdapter<String> {

    private static final int ITEM_HEIGHT = ViewGroup.LayoutParams.WRAP_CONTENT;

    private int textViewResourceId;


    public MyArrayAdapter(Context context,
                          int textViewResourceId,
                          String[] objects) {
        super(context, textViewResourceId, objects);
        this.textViewResourceId = textViewResourceId;
    }

    @Override
    public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
        TextView textView;

        if (convertView == null) {
            textView = (TextView) LayoutInflater.from(getContext())
                   .inflate(textViewResourceId, parent, false);
        } else {
            textView = (TextView) convertView;
        }

        textView.setText(getItem(position));
        if (position == 0) {
            ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
            layoutParams.height = 1;
            textView.setLayoutParams(layoutParams);
        } else {
            ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
            layoutParams.height = ITEM_HEIGHT;
            textView.setLayoutParams(layoutParams);
        }

        return textView;
    }
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*itt 6

我参加派对有点晚了,但这就是我为解决这个问题所做的.
如果用户取消选择初始项目,则微调器将保持初始空状态.一旦选择了初始项目,它就像'正常'一样
工作在2.3.3+上,我没有在2.2及以下测试过.

首先,创建一个适配器类......

public class EmptyFirstItemAdapter extends ArrayAdapter<String>{
    //Track the removal of the empty item
    private boolean emptyRemoved = false;

    /** Adjust the constructor(s) to fit your purposes. */
    public EmptyFirstitemAdapter(Context context, List<String> objects) {
        super(context, android.R.layout.simple_spinner_item, objects);
        setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    }

    @Override
    public int getCount() {
        //Adjust the count based on the removal of the empty item
        if(emptyRemoved){
            return super.getCount();            
        }
        return super.getCount()-1;            
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if(!emptyRemoved){
            // Remove the empty item the first time the dropdown is displayed.
            emptyRemoved = true;
            // Set to false to prevent auto-selecting the first item after removal.
            setNotifyOnChange(false);
            remove(getItem(0));
            // Set it back to true for future changes.
            setNotifyOnChange(true);
        }
        return super.getDropDownView(position, convertView, parent);
    }

    @Override
    public long getItemId(int position) {
        // Adjust the id after removal to keep the id's the same as pre-removal.
        if(emptyRemoved){
            return position +1;
        }
        return position;
    }

}
Run Code Online (Sandbox Code Playgroud)

这是我在strings.xml中使用的字符串数组

<string-array name="my_items">
    <item></item>
    <item>Item 1</item>
    <item>Item 2</item>
</string-array>
Run Code Online (Sandbox Code Playgroud)

接下来,将OnItemSelectedListener添加到Spinner中......

mSpinner = (Spinner) mRootView.findViewById(R.id.spinner);
String[] opts = getResources().getStringArray(R.array.my_items);
//DO NOT set the entries in XML OR use an array directly, the adapter will get an immutable List.
List<String> vals = new ArrayList<String>(Arrays.asList(opts));
final EmptyFirstitemAdapter adapter = new EmptyFirstitemAdapter(getActivity(), vals);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    //Track that we have updated after removing the empty item
    private boolean mInitialized = false;
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if(!mInitialized && position == 0 && id == 1){
            // User selected the 1st item after the 'empty' item was initially removed,
            // update the data set to compensate for the removed item.
            mInitialized = true;
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // Nothing to do
    }
});
Run Code Online (Sandbox Code Playgroud)

它可能不是一个"完美"的解决方案,但我希望它可以帮助某人.


小智 -1

您必须将微调器的第一个元素设置为空,或者指示string未选择任何内容,如下所示:

String[] ch= {"","Session1", "Session2", "Session3"};
Run Code Online (Sandbox Code Playgroud)

或者

String[] ch= {"Nothing selected", "Session1", "Session2", "Session3"};
Run Code Online (Sandbox Code Playgroud)

希望能有所帮助