我在一个android项目上工作,我正在使用一个旋转器,它使用一个从数据库填充的数组适配器。
我不知道如何从列表中以编程方式设置所选项目。例如,如果在旋转器中有以下项目:
类别1 第二类 3级
当创建屏幕时,我如何通过编程使类别2成为所选项目。我在想它可能类似于c#的i.e. Spinner。SelectedText = "Category 2"但似乎没有任何方法类似于Android。
我在一个android项目上工作,我正在使用一个旋转器,它使用一个从数据库填充的数组适配器。
我不知道如何从列表中以编程方式设置所选项目。例如,如果在旋转器中有以下项目:
类别1 第二类 3级
当创建屏幕时,我如何通过编程使类别2成为所选项目。我在想它可能类似于c#的i.e. Spinner。SelectedText = "Category 2"但似乎没有任何方法类似于Android。
当前回答
这是我在Kotlin中使用的:
spinner.setSelection(resources.getStringArray(R.array.choices).indexOf("Choice 1"))
其他回答
我有一个SimpleCursorAdapter,所以我必须复制在这篇文章中使用响应的数据。所以,我建议你试试这个方法:
for (int i = 0; i < spinnerRegion.getAdapter().getCount(); i++) {
if (spinnerRegion.getItemIdAtPosition(i) == Integer
.valueOf(signal.getInt(signal
.getColumnIndexOrThrow("id_region")))) {
spinnerRegion.setSelection(i);
break;
}
}
我认为这是一个真正的方法
Some explanation (at least for Fragments - never tried with pure Activity). Hope it helps someone to understand Android better. Most popular answer by Arun George is correct but don't work in some cases. The answer by Marco HC uses Runnable wich is a last resort due to additional CPU load. The answer is - you should simply choose correct place to call to setSelection(), for example it works for me: @Override public void onResume() { super.onResume(); yourSpinner.setSelection(pos); } But it won't work in onCreateView(). I suspect that is the reason for the interest to this topic. The secret is that with Android you can't do anything you want in any method - oops:( - components may just not be ready. As another example - you can't scroll ScrollView neither in onCreateView() nor in onResume() (see the answer here)
这在本页其他地方的评论中有说明,但我认为把它拉出来作为一个答案是有用的:
当使用适配器时,我发现spinnerObject.setSelection(INDEX_OF_CATEGORY2)需要发生在setAdapter调用之后;否则,第一项总是初始选择。
// spinner setup...
spinnerObject.setAdapter(myAdapter);
spinnerObject.setSelection(INDEX_OF_CATEGORY2);
这可以通过检查setAdapter的AbsSpinner代码来确认。
我从昨天开始就有同样的问题。不幸的是,数组列表中的第一项默认显示在spinner小部件中。一种转换方法是在数组列表中找到带有每个元素的前一个选定项,并将其与第一个元素交换位置。这是代码。
OnResume()
{
int before_index = ShowLastSelectedElement();
if (isFound){
Collections.swap(yourArrayList,before_index,0);
}
adapter = new ArrayAdapter<String>(CurrentActivity.this,
android.R.layout.simple_spinner_item, yourArrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item; yourListView.setAdapter(adapter);
}
...
private int ShowLastSelectedElement() {
String strName = "";
int swap_index = 0;
for (int i=0;i<societies.size();i++){
strName = yourArrayList.get(i);
if (strName.trim().toLowerCase().equals(lastselectedelement.trim().toLowerCase())){
swap_index = i;
isFound = true;
}
}
return swap_index;
}
for (int x = 0; x < spRaca.getAdapter().getCount(); x++) {
if (spRaca.getItemIdAtPosition(x) == reprodutor.getId()) {
spRaca.setSelection(x);
break;
}
}