从Android Spinner显示所选字符串

时间:2016-10-01 20:43:48

标签: java android

    String chooseTime[] = {"7.00 - 9.00", "9.00 - 11.00", "11.00 - 13.00", "13.00 - 15.00", "15.00 - 17.00", "17.00 - 18.30" };
    spTimeConsegna = (Spinner)     
    rootView.findViewById(R.id.timeChooseConsegna);
    adapterChooseTimeConsegna = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, chooseTime);
    adapterChooseTimeConsegna.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spTimeConsegna.setAdapter(adapterChooseTimeConsegna);

    chooseTimeConsegna = chooseTime[spTimeConsegna.getSelectedItemPosition()];

我想在chooseTimeConsegna字符串中保存微调器的选定值,但它总是无差别地保存chooseTime字符串数组的第一个值在微调器中选择的内容。为什么呢?

2 个答案:

答案 0 :(得分:0)

我认为你是在onCreate方法中执行此操作,因此只在启动该活动时调用它,而不是每次在微调器上选择事物时调用它。尝试这样的事情:

yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        String chooseTime[] = {"7.00 - 9.00", "9.00 - 11.00", "11.00 - 13.00", "13.00 - 15.00", "15.00 - 17.00", "17.00 - 18.30" };
        chooseTimeConsegna = chooseTime[position];
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
    }
});

每次在微调器上选择某个东西时都会调用此方法,参数position是微调器中所选项的位置。

答案 1 :(得分:0)

替换:

chooseTimeConsegna = chooseTime[spTimeConsegna.getSelectedItemPosition()];

使用:

spTimeConsegna.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        chooseTimeConsegna = chooseTime[position];
    }
});

你应该好好去。