Android微调器设置值

时间:2012-07-25 18:20:04

标签: android android-spinner

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

这是我到目前为止所做的:

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;

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

3 个答案:

答案 0 :(得分:10)

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

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

显然,如果你的模型不包含任何'name'数据,那么在Spinner中没有什么可以选择的,所以你可能想要添加一些逻辑来处理它。如果模型确实具有“名称”,则在原始列表中查找其索引,该列表用作适配器的数据源。仅在找到事件时,将微调器的选择设置为相同的索引。

答案 1 :(得分:2)

我以编程方式设置微调器值:

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                   
        }
    });               
}

答案 2 :(得分:0)

在科特林,它将是这样的:

spinner.adapter = ArrayAdapter(
            context,
            android.R.layout.simple_list_item_1,
            stringList
)