慕的地6264312
我编写了MultiSpinner的自定义实现。它看起来类似于普通的微调器,但它有复选框而不是radiobuttons。选定的值显示在微调器上除以逗号。默认情况下会检查所有值。试试吧:package cz.destil.settleup.gui;public class MultiSpinner extends Spinner implements OnMultiChoiceClickListener, OnCancelListener { private List<String> items; private boolean[] selected; private String defaultText; private MultiSpinnerListener listener; public MultiSpinner(Context context) { super(context); } public MultiSpinner(Context arg0, AttributeSet arg1) { super(arg0, arg1); } public MultiSpinner(Context arg0, AttributeSet arg1, int arg2) { super(arg0, arg1, arg2); } @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) selected[which] = true; else selected[which] = false; } @Override public void onCancel(DialogInterface dialog) { // refresh text on spinner StringBuffer spinnerBuffer = new StringBuffer(); boolean someUnselected = false; for (int i = 0; i < items.size(); i++) { if (selected[i] == true) { spinnerBuffer.append(items.get(i)); spinnerBuffer.append(", "); } else { someUnselected = true; } } String spinnerText; if (someUnselected) { spinnerText = spinnerBuffer.toString(); if (spinnerText.length() > 2) spinnerText = spinnerText.substring(0, spinnerText.length() - 2); } else { spinnerText = defaultText; } ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, new String[] { spinnerText }); setAdapter(adapter); listener.onItemsSelected(selected); } @Override public boolean performClick() { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMultiChoiceItems( items.toArray(new CharSequence[items.size()]), selected, this); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setOnCancelListener(this); builder.show(); return true; } public void setItems(List<String> items, String allText, MultiSpinnerListener listener) { this.items = items; this.defaultText = allText; this.listener = listener; // all selected by default selected = new boolean[items.size()]; for (int i = 0; i < selected.length; i++) selected[i] = true; // all text on the spinner ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, new String[] { allText }); setAdapter(adapter); } public interface MultiSpinnerListener { public void onItemsSelected(boolean[] selected); }}你在XML中使用它像这样:<cz.destil.settleup.gui.MultiSpinner android:id="@+id/multi_spinner" />你用Java将数据传递给它:MultiSpinner multiSpinner = (MultiSpinner) findViewById(R.id.multi_spinner);multiSpinner.setItems(items, getString(R.string.for_all), this);你还需要实现一个监听器,它将返回相同长度的数组,使用true或false来显示所选的未选择状态。public void onItemsSelected(boolean[] selected);