如何将Spinner默认值设置为null?

时间:2011-01-18 16:34:23

标签: android android-spinner

我正在尝试让Spinner加载时没有选定的值。一旦用户选择了一个值,它就会将它们带到另一个页面。

这被证明是一个问题,因为目前,该页面只是在用户可以选择之前立即加载。

我的微调器类的设置方式与Google的相同:http://developer.android.com/resources/tutorials/views/hello-spinner.html

所以基本上,是否有可能有一个微调器加载没有选择,因为目前,它加载我的字符串数组中的第一个项目。

11 个答案:

答案 0 :(得分:78)

  

是否可能有一个没有选择加载的微调器

仅在没有数据的情况下。如果SpinnerAdapter中有1个以上的项目,Spinner将始终有选择。

Spinners并非设计为命令小部件。用户不希望在Spinner中选择启动活动。请考虑使用其他内容,例如ListViewGridView,而不是Spinner


修改

BTW,我忘了提及 - 你总是可以在适配器中添加一个代表“无选择”的额外条目,并将其作为Spinner中的初始选定项目。

答案 1 :(得分:28)

或者,您可以覆盖您的微调器适配器,并为getView方法中的位置0提供空视图,并在getDropDownView方法中提供高度为0dp的视图。

这样,您有一个初始文本,例如“选择一个选项...”,它在首次加载微调器时显示,但它不是用户选择的选项(从技术上来说,但是因为高度为0,他们看不到它。)

答案 2 :(得分:17)

这是Paul Bourdeaux's idea的完整实现,即在getView()中为位置0返回特殊的初始视图(或空视图)。

它对我有用,而且相对简单。如果您的Spinner已经有自定义适配器,您可能会考虑使用此方法,尤其是。 (在我的例子中,我使用自定义适配器,以便轻松自定义项目的布局,每个项目都有几个TextView。)

适配器将是这些方面的东西:

public class MySpinnerAdapter extends ArrayAdapter<MyModel> {

    public MySpinnerAdapter(Context context, List<MyModel> items) {
        super(context, R.layout.my_spinner_row, items);
    }

    @Override
    public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
        if (position == 0) {
            return initialSelection(true);
        }
        return getCustomView(position, convertView, parent);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        if (position == 0) {
            return initialSelection(false);
        }
        return getCustomView(position, convertView, parent);
    }


    @Override
    public int getCount() {
        return super.getCount() + 1; // Adjust for initial selection item
    }

    private View initialSelection(boolean dropdown) {
        // Just an example using a simple TextView. Create whatever default view 
        // to suit your needs, inflating a separate layout if it's cleaner.
        TextView view = new TextView(getContext());
        view.setText(R.string.select_one);
        int spacing = getContext().getResources().getDimensionPixelSize(R.dimen.spacing_smaller);
        view.setPadding(0, spacing, 0, spacing);

        if (dropdown) { // Hidden when the dropdown is opened
            view.setHeight(0);
        }

        return view;
    }

    private View getCustomView(int position, View convertView, ViewGroup parent) {
        // Distinguish "real" spinner items (that can be reused) from initial selection item
        View row = convertView != null && !(convertView instanceof TextView) 
        ? convertView :
        LayoutInflater.from(getContext()).inflate(R.layout.my_spinner_row, parent, false);

        position = position - 1; // Adjust for initial selection item
        MyModel item = getItem(position);

        // ... Resolve views & populate with data ...

        return row;
    }

}

那就是它。请注意,如果您使用OnItemSelectedListener与您的微调器,onItemSelected(),您还必须调整position以考虑默认项目,例如:

if (position == 0) {
    return;
} else {
    position = position - 1;
}
MyModel selected = items.get(position);

答案 3 :(得分:5)

在我的情况下,虽然在微调器中显示大小'2',但在完成某些选择之前没有任何反应!

我有一个xml文件(data_sizes.xml),其中列出了所有微调器值。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="chunks">
        <item>2</item>
        <item>4</item>
        <item>8</item>
        <item>16</item>
        <item>32</item>
    </string-array>
</resources>    

在main.xml文件中:Spinner元素

<Spinner android:id="@+id/spinnerSize"  
android:layout_marginLeft="50px"
android:layout_width="fill_parent"                  
android:drawSelectorOnTop="true"
android:layout_marginTop="5dip"
android:prompt="@string/SelectSize"
android:layout_marginRight="30px"
android:layout_height="35px" /> 

然后在我的java代码中,我添加了:

在我的活动中:宣言

Spinner spinnerSize;
ArrayAdapter adapter;

在公共void函数中 - initControls():Definition

spinnerSize = (Spinner)findViewById(R.id.spinnerSize);
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSize.setAdapter(adapter);
spinnerSize.setOnItemSelectedListener(new MyOnItemSelectedListener());

我的傻瓜听众:

/ * Spinner Listener * /

class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent,
        View view, int pos, long id) {
        chunkSize = new Integer(parent.getItemAtPosition(pos).toString()).intValue();
    }
    public void onNothingSelected(AdapterView<?> parent) {
      // Dummy
    }
}

答案 4 :(得分:3)

使用这样的自定义微调器布局:

<?xml version="1.0" encoding="utf-8"?>
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/spinnerTarget"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:textSize="14dp"         
          android:textColor="#000000"/>

在活动中:

    // populate the list
    ArrayList<String> dataList = new ArrayList<String>();
    for (int i = 0; i < 4; i++) {
        dataList.add("Item");
    }

    // set custom layout spinner_layout.xml and adapter
    Spinner spinnerObject = (Spinner) findViewById(R.id.spinnerObject);
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.drawable.spinner_layout, dataList);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerObject.setAdapter(dataAdapter);
    spinnerObject.setOnTouchListener(new View.OnTouchListener() { 

        public boolean onTouch(View v, MotionEvent event) {
            // to set value of first selection, because setOnItemSelectedListener will not dispatch if the user selects first element
            TextView spinnerTarget = (TextView)v.findViewById(R.id.spinnerTarget);
            spinnerTarget.setText(spinnerObject.getSelectedItem().toString());

            return false;
        }

    });
    spinnerObject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                private boolean selectionControl = true;

                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                    // just the first time
                    if(selectionControl){

                        // find TextView in layout 
                        TextView spinnerTarget = (TextView)parent.findViewById(R.id.spinnerTarget);
                        // set spinner text empty
                        spinnerTarget.setText("");
                        selectionControl = false;
                    }
                    else{
                        // select object
                    }
                }

                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

答案 5 :(得分:3)

合并:

private long previousItemId = 0;

@Override
public long getItemId(int position) {
    long nextItemId = random.nextInt(Integer.MAX_VALUE);
    while(previousItemId == nextItemId) {
        nextItemId = random.nextInt(Integer.MAX_VALUE);
    }
    previousItemId = nextItemId;
    return nextItemId;
}

使用此answer

public class SpinnerInteractionListener
        implements AdapterView.OnItemSelectedListener, View.OnTouchListener {

    private AdapterView.OnItemSelectedListener onItemSelectedListener;

    public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
        this.onItemSelectedListener = selectedListener;
    }

    boolean userSelect = false;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        userSelect = true;
        return false;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        if(userSelect) {
            onItemSelectedListener.onItemSelected(parent, view, pos, id);
            userSelect = false;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        if(userSelect) {
            onItemSelectedListener.onNothingSelected(parent);
            userSelect = false;
        }
    }
}

答案 6 :(得分:1)

你可以将数组中的第一个单元格设置为空({&#34;&#34;,&#34;某些&#34;,&#34;某些&#34;,...}} 如果位置为0,则不执行任何操作;

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    if(position>0) {
        label.setText(MainActivity.questions[position - 1]);
    }
}
  • 如果您通过xml文件填充数组,则可以将第一个项目清空

答案 7 :(得分:1)

我的解决方案,如果你有一个TextView作为微调器的每一行:

    // TODO: add a fake item as the last one of "items"
    final ArrayAdapter<String> adapter=new ArrayAdapter<String>(..,..,items) 
      {
      @Override
      public View getDropDownView(final int position,final View convertView,final ViewGroup parent)
        {
        final View dropDownView=super.getDropDownView(position,convertView,parent);
        ((TextView)dropDownView.findViewById(android.R.id.text1)).setHeight(position==getCount()-1?0:getDimensionFromAttribute(..,R.attr.dropdownListPreferredItemHeight));
        dropDownView.getLayoutParams().height=position==getCount()-1?0:LayoutParams.MATCH_PARENT;
        return dropDownView;
        }
      }

    ...
    spinner.setAdapter(adapter);
    _actionModeSpinnerView.setSelection(dataAdapter.getCount()-1,false);



  public static int getDimensionFromAttribute(final Context context,final int attr)
    {
    final TypedValue typedValue=new TypedValue();
    if(context.getTheme().resolveAttribute(attr,typedValue,true))
      return TypedValue.complexToDimensionPixelSize(typedValue.data,context.getResources().getDisplayMetrics());
    return 0;
    }

答案 8 :(得分:0)

基于@Jonik答案,我已经创建了ArrayAdapter的全功能扩展

class SpinnerArrayAdapter<T> : ArrayAdapter<T> {

    private val selectText : String
    private val resource: Int
    private val fieldId : Int
    private val inflater : LayoutInflater

    constructor(context: Context?, resource: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, objects) {
        this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
        this.resource = resource
        this.fieldId = 0
        this.inflater = LayoutInflater.from(context)
    }
    constructor(context: Context?, resource : Int, objects: List<T>, selectText : String? = null) : super(context, resource, objects) {
        this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
        this.resource = resource
        this.fieldId = 0
        this.inflater = LayoutInflater.from(context)
    }
    constructor(context: Context?, resource: Int, textViewResourceId: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
        this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
        this.resource = resource
        this.fieldId = textViewResourceId
        this.inflater = LayoutInflater.from(context)
    }
    constructor(context: Context?, resource : Int, textViewResourceId: Int, objects: List<T>, selectText : String? = null) : super(context, resource, textViewResourceId,  objects) {
        this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
        this.resource = resource
        this.fieldId = textViewResourceId
        this.inflater = LayoutInflater.from(context)
    }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
        if(position == 0) {
            return initialSelection(true)
        }

        return createViewFromResource(inflater, position -1, convertView, parent, resource)
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        if(position == 0) {
            return initialSelection(false)
        }
        return createViewFromResource(inflater, position -1, convertView, parent, resource)
    }

    override fun getCount(): Int {
        return super.getCount() + 1 // adjust for initial selection
    }

    private fun initialSelection(inDropDown: Boolean) : View {
        // Just simple TextView as initial selection.
        val view = TextView(context)
        view.setText(selectText)
        view.setPadding(8, 0, 8, 0)

        if(inDropDown) {
            // Hide when dropdown is open
            view.height = 0
        }
        return view
    }

    private fun createViewFromResource(inflater: LayoutInflater, position: Int,
                                       @Nullable convertView: View?, parent: ViewGroup?, resource: Int): View {
        val view: View
        val text: TextView?

        if (convertView == null || (convertView is TextView)) {
            view = inflater.inflate(resource, parent, false)
        } else {
            view = convertView
        }

        try {
            if (fieldId === 0) {
                //  If no custom field is assigned, assume the whole resource is a TextView
                text = view as TextView
            } else {
                //  Otherwise, find the TextView field within the layout
                text = view.findViewById(fieldId)

                if (text == null) {
                    throw RuntimeException("Failed to find view with ID "
                            + context.getResources().getResourceName(fieldId)
                            + " in item layout")
                }
            }
        } catch (e: ClassCastException) {
            Log.e("ArrayAdapter", "You must supply a resource ID for a TextView")
            throw IllegalStateException(
                    "ArrayAdapter requires the resource ID to be a TextView", e)
        }

        val item = getItem(position)
        if (item is CharSequence) {
            text.text = item
        } else {
            text.text = item!!.toString()
        }

        return view
    }

答案 9 :(得分:0)

我假设您想拥有一个Spinner,其中第一个空的不可见项目(这是Spinner的一个奇怪功能,如果不选择项目就无法显示列表)。您应该添加一个包含数据的类:

data class YourData(val id: Int, val name: String?)

这是适配器。

class YourAdapter(
    context: Context,
    private val textViewResourceId: Int,
    private var items: ArrayList<YourData>
) : ArrayAdapter<YourData>(context, textViewResourceId, items) {

    private var inflater: LayoutInflater = context.getSystemService(
        Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

    override fun getCount(): Int = items.size + 1

    override fun getItem(position: Int): YourData? =
        if (position == 0) YourData(0, "") else items[position - 1]

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View =
        if (position == 0) {
            getFirstTextView(convertView)
        } else {
            getTextView(convertView, parent, position - 1)
        }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View =
        getView(position, convertView, parent)

    private fun getFirstTextView(convertView: View?): View {
        // Just simple TextView as initial selection.
        var textView: TextView? = convertView as? TextView
        val holder: FirstViewHolder
        if (textView?.tag !is FirstViewHolder) {
            textView = TextView(context) // inflater.inflate(R.layout.your_text, parent, false) as TextView
            textView.height = 0 // Hide first item.
            holder = FirstViewHolder()
            holder.textView = textView
            textView.tag = holder
        }
        return textView
    }

    private fun getTextView(
        convertView: View?,
        parent: ViewGroup,
        position: Int
    ): TextView {
        var textView: TextView? = convertView as? TextView
        val holder: ViewHolder
        if (textView?.tag is ViewHolder) {
            holder = textView.tag as ViewHolder
        } else {
            textView = inflater.inflate(textViewResourceId, parent, false) as TextView
            holder = ViewHolder()
            holder.textView = textView
            textView.tag = holder
        }
        holder.textView.text = items[position].name

        return textView
    }

    private class FirstViewHolder {
        lateinit var textView: TextView
    }

    private class ViewHolder {
        lateinit var textView: TextView
    }
}

要创建:

YourAdapter(context!!, R.layout.text_item, ArrayList())

要添加项目:

private fun fill(items: List<YourData>, adapter: YourAdapter) {
    adapter.run {
        clear()
        addAll(items)
        notifyDataSetChanged()
    }
}

使用该Spinner命令将项目加载到fill()时,应该知道索引也会增加。因此,如果您希望选择第3个项目,则现在应选择第4个:spinner?.setSelection(index + 1)

答案 10 :(得分:0)

说明 - 我们可以将 arrayList 的第一个参数中的虚拟值发送到微调适配器。然后将我们在 arrayList 中的虚拟值的位置(0 或 arrayList 之间的任何一个)发送到 SpinnerAdapter 构造函数。

public void addDataToList(LstQRTrackingSummary qrTrackingSummary) {
        SpinnerMenu mSpinnerMenuzero = new SpinnerMenu();
        mSpinnerMenuzero.setName("Select Action");
        spinner_list.add(mSpinnerMenuzero);

        if (qrTrackingSummary.getOQRTrackingButtons().getBtnToDispatch()) {
            SpinnerMenu mSpinnerMenu = new SpinnerMenu();
            mSpinnerMenu.setName("Dispatch");
            mSpinnerMenu.setmDrawable(ResourcesCompat.getDrawable(context.getResources(),R.drawable.ic_dispatch,null));
            spinner_list.add(mSpinnerMenu);
        }

        if (qrTrackingSummary.getOQRTrackingButtons().getBtnForwardToDispatch()) {
            SpinnerMenu mSpinnerMenu = new SpinnerMenu();
            mSpinnerMenu.setName("Forward To Dispatch");
            mSpinnerMenu.setmDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_forward_to_dispatch, null));
            spinner_list.add(mSpinnerMenu);
        }
  }

然后在微调适配器类中以与我所做的相同的方式隐藏它并完成。

public class SpinnerAdapter extends ArrayAdapter<SpinnerMenu> {

private Context context;
private ArrayList<SpinnerMenu> menuList;
private LayoutInflater inflater;
private SpinnerMenu spinnerMenu;
public Integer positionToHide ;

public SpinnerAdapter(Context context, Integer positionToHide,ArrayList<SpinnerMenu> menuList) {
    super(context, 0, menuList);
    this.context = context;
    this.positionToHide = positionToHide ;
    inflater = LayoutInflater.from(context);
    this.menuList = menuList;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    return getCustomView(position, convertView, parent);
}

@Override
public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    return getCustomView(position, convertView, parent);
}

private View getCustomView(int position, View convertView , ViewGroup parent) {
    View view = null ;
    if (view == null) {
        view = inflater.inflate(R.layout.spinner_baseview, parent, false);
    }

    ImageView spin_image = view.findViewById(R.id.spinner_image);
    TextView spin_text = view.findViewById(R.id.spinner_text);
    spinnerMenu = menuList.get(position);

    if (position == positionToHide) {
        TextView mytext = new TextView(context);
        mytext.setVisibility(View.GONE);
        mytext.setHeight(0);
        view = mytext;
        view.setVisibility(View.GONE);
    } else {
        spin_image.setImageDrawable(spinnerMenu.getmDrawable());
        spin_text.setText(spinnerMenu.getName());
    }
    return view;
}

}