我使用MaterialBetterSpinner库作为微调器但不能设置为指定位置。
String[] LIST = {"Item1", "Item2", "Item3", "Item4", "Item5"};
MaterialBetterSpinner spinnerItem = (MaterialBetterSpinner) findViewById(R.id.spinnerItem);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, LIST);
String str = "Item3";
for(int i=0; i < adapter1.getCount(); i++) {
if(str.trim().equals(adapter1.getItem(i).toString())){
spinnerItem.setSelection(i);
break;
}
}
我得到以下异常
Caused by: java.lang.IndexOutOfBoundsException: setSpan (1 ... 1) ends beyond length 0
答案 0 :(得分:3)
根据此issue,解决方案是使用 getText()
因此,您可以使用默认值执行此操作
String[] LIST = {"Item1", "Item2", "Item3", "Item4", "Item5"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, LIST);
spinner1.setAdapter(adapter);
spinner2.setAdapter(adapter);
String str = "Item3";
for(int i=0; i < adapter.getCount(); i++) {
if(str.trim().equals(adapter.getItem(i).toString())){
spinner2.setText(adapter.getItem(i).toString());
break;
}
}
答案 1 :(得分:1)
这是来自Android开发者
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
创建适配器后,您只需拨打spinner.setAdapter(adapter)
而不是每个项目
修改强> 将特定项目设置为默认值
String string = 'my string';
int spinnerPosition = adapter.getPosition(string);
spinner.setSelection(spinnerPosition);
编辑2: 由于Jorge Casariego也指出了问题(https://github.com/Lesilva/BetterSpinner/issues/13),请使用setText但如果您知道该字符串位于微调器中,则可以仅使用
来改进其代码spinner.setText(string)