要按值设置Spinner的选定项,请返回-1

时间:2017-06-07 10:31:09

标签: android spinner android-spinner android-studio-2.3

我使用以下代码按值设置微调器的选定项。但我得到的位置是-1。

代码:

final ArrayAdapter<CharSequence> adapter1 = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_list_item_1, location_days2);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        location_days.setAdapter(adapter1);
        String b = "5 Days"; 
        int a = adapter.getPosition(b); //this should return 5, but returns -1
        location_days.setSelection(a);

字符串数组:

private String [] location_days2 = {“选择日期”,“1天”,“2天”,“3天”,“0天”,“5天”,“6天”};

2 个答案:

答案 0 :(得分:1)

public ActionResult ActionName(model modelName)

在上面的行中用 adapter1 替换适配器,因为您已将适配器初始化为&#34; adapter1&#34;

答案 1 :(得分:0)

您可以执行以下操作来在微调器中设置选择

int pos = 0;
String[] location_days2 = {"Select days", "1 Day", "2 Days", "3 Days", "0 Days", "5 Days", "6 Days"};
for (String location : location_days2) {
   if (location.equalsIgnoreCase("5 Days")) {
       pos = Arrays.asList(location_days2).indexOf("23");
       break;
      }
    }
location_days.setSelection(pos);