如何在android中动态地向微调器添加项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2160518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to add items to the spinner dynamically in android?
提问by deepthi
how to add items to the spinner dynamically in android?
如何在android中动态地向微调器添加项目?
回答by DAS
Spinner spinner = (Spinner)findViewById(R.id.mySpinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, android.R.id.text1);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinnerAdapter.add("value");
spinnerAdapter.notifyDataSetChanged();
the above is in case of the array adapter, I believe you know how to populate values with ArrayAdapter .
以上是数组适配器的情况,我相信您知道如何使用 ArrayAdapter 填充值。
How can we do this in case of the SimpleCursorAdapter, i.e if we have 2 spinners and if we select the values of one spinner (that is getting the value from SimpleCursorAdapter) depending on some criteria the other spinner should be filled with values. how can we achieve that?
在 SimpleCursorAdapter 的情况下我们如何做到这一点,即如果我们有 2 个微调器,并且如果我们根据某些标准选择一个微调器的值(即从 SimpleCursorAdapter 获取值),另一个微调器应该填充值。我们怎样才能做到这一点?
回答by JRL
By calling ArrayAdapter.add
to the Spinner's ArrayAdapter.
通过调用ArrayAdapter.add
Spinner 的 ArrayAdapter。
回答by Md. Al Amin Bhuiyan
You can follow this way
你可以按照这个方式
public static void selectSpinnerItemByValue(Spinner spnr, long value){
SimpleCursorAdapter adapter = (SimpleCursorAdapter) spnr.getAdapter();
for (int position = 0; position < adapter.getCount(); position++)
{
if(adapter.getItemId(position) == value)
{
spnr.setSelection(position);
return;
}
} }
You can use the above like:
您可以使用上述内容,例如:
selectSpinnerItemByValue(spinnerObject, desiredValue);
you can also select by index directly like
您也可以直接按索引选择
spinnerObject.setSelection(index);