8

我想在运行时设置 android spinner item 值。

这是我到目前为止所拥有的:

final ArrayAdapter<String> calsListAdapter = new ArrayAdapter<String>( this,
                android.R.layout.simple_list_item_1, calendarNames);
eventCalendarList.setAdapter(calsListAdapter);
eventCalendarList.setOnItemSelectedListener(new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        calendarChoosen = availableCals.get(arg2);
    }
    public void onNothingSelected(AdapterView<?> arg0) {
        Logger.d("Cal Choosen", "fffffffffffffff");
    }
});

private List<AvailableCalendar> availableCals = new ArrayList<AvailableCalendar>();
private AvailableCalendar calendarChoosen;

但是没有设置值。怎么做到呢?

4

3 回答 3

11

我将在这里假设您基于 aList<CharSequence>或类似的东西创建 Spinner 的适配器。您可以使用它来查找选择,例如:

String name = model.getName();
int index = list.indexOf(name);
if (index != -1) spinner.setSelection(index);

显然,如果您的模型不包含任何“名称”数据,则在 Spinner 中没有任何选择,因此您可能需要添加一些逻辑来处理它。如果模型确实有一个“名称”,则在用作适配器数据源的原始列表中找到它的索引。仅当找到一个事件时,将微调器的选择设置为相同的索引。

于 2012-07-25T19:39:07.023 回答
3

我以编程方式设置微调器值,如下所示:

public class MainActivity extends Activity {
    private SharedPreferences prefs;
    private String prefName = "spinner_value";
    int id=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final List<String> list=new ArrayList<String>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");

        final Spinner sp=(Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<String> adp= new ArrayAdapter<String>(this,
                                    android.R.layout.simple_list_item_1,list);
        adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp.setAdapter(adp);

        prefs = getSharedPreferences(prefName, MODE_PRIVATE);
        id=prefs.getInt("last_val",0);
        sp.setSelection(id);

        sp.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, 
                View arg1,int pos, long arg3) {

            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            //---save the values in the EditText view to preferences---
            editor.putInt("last_val", pos);

            editor.commit();

            Toast.makeText(getBaseContext(), 
                sp.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub                   
        }
    });               
}
于 2012-07-30T23:44:24.567 回答
0

在 kotlin 中会是这样的:

spinner.adapter = ArrayAdapter(
            context,
            android.R.layout.simple_list_item_1,
            stringList
)
于 2020-09-08T12:43:56.487 回答