[英]Set selected spinner item based on a name, not a position in Android
I have three spinners in an activity where I can edit information that the user has already entered into a database. 我有一个活动中的三个微调器,可以在其中编辑用户已经输入数据库的信息。 I have been able to set the text of a textfield by querying my SQLite database to match what the user can edit. 通过查询SQLite数据库以匹配用户可以编辑的内容,我已经能够设置文本字段的文本。 Can the same be done with a spinner? 旋转器可以做同样的事情吗?
For example, if a user picked the year 2000 previously, in the new edit activity I want the spinner to be already selected at 2000 and then they can change this if they want to. 例如,如果用户以前选择了2000年,那么在新的编辑活动中,我希望已在2000年选择了微调框,然后他们可以根据需要进行更改。
So far I have only seen options to set positions of spinners based on an integer position. 到目前为止,我只看到基于整数位置设置微调器位置的选项。 Can this be done by providing a year? 能提供一年吗? Thanks for any help. 谢谢你的帮助。
Here's what I am currently working on with my month spinner: 这是我目前正在使用我的月份微调器的内容:
ArrayList<String> list = new ArrayList( Arrays.asList(getResources().getStringArray(R.array.months)) );
int pos = list.get("March");
spinMonth.setSelection(pos);
All you can do is identifying the position of the item in the spinner and the setting the selection of spinner. 您所能做的就是确定项目在微调器中的位置并设置微调器的选择。
int pos=yourlist.indexOf("2000");
spinner.setSelection(pos);
Edit: 编辑:
ArrayList<String> list=new ArrayList( Arrays.asList(getResources().getStringArray(R.array.years)) ); // your array id of string resource
int pos= list.indexOf("2000");
spinner.setSelection(pos);
I had to do the exact same thing the other week. 前一周我不得不做完全相同的事情。 Here was my approach. 这是我的方法。
String userName = dataCursor.getString(dataCursor.getColumnIndex("USER_NAME"));
int position = listOfUsers.indexOf(userName);
userSpinner.setSelection(position);
where listOfUsers
is the list I use to popular the Spinner, userSpinner
. 其中listOfUsers
是我用来流行Spinner的列表userSpinner
。 Hope that helps! 希望有帮助!
简单的一行代码是
spinMonth.setSelection(Arrays.asList(getResources().getStringArray(R.array.months)).indexOf("March"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.