I have a update view, where I need to preselect the value stored in database for a Spinner.
我有一个update视图,需要在其中预先选择存储在数据库中的用于微调器的值。
I was having in mind something like this, but the Adapter
has no indexOf
method, so I am stuck.
我的想法是这样的,但是适配器没有indexOf方法,所以我被卡住了。
void setSpinner(String value)
{
int pos = getSpinnerField().getAdapter().indexOf(value);
getSpinnerField().setSelection(pos);
}
21 个解决方案
#1
534
Suppose your Spinner
is named mSpinner
, and it contains as one of its choices: "some value".
假设您的Spinner被命名为mSpinner,它包含了它的一个选择:“一些值”。
To find and compare the position of "some value" in the Spinner use this:
为了找到并比较“某些值”在纺纱器中的位置,使用以下方法:
String compareValue = "some value";
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
if (compareValue != null) {
int spinnerPosition = adapter.getPosition(compareValue);
mSpinner.setSelection(spinnerPosition);
}
#2
105
A simple way to set spinner based on value is
一种基于值设置微调控制项的简单方法是
mySpinner.setSelection(getIndex(mySpinner, myValue));
//private method of your class
private int getIndex(Spinner spinner, String myString){
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)){
return i;
}
}
return 0;
}
Way to complex code are already there, this is just much plainer.
到复杂代码的方法已经在那里了,这是非常简单的。
#3
34
I keep a separate ArrayList of all the items in my Spinners. This way I can do indexOf on the ArrayList and then use that value to set the selection in the Spinner.
我在我的旋转器中保存了一个单独的数组列表。这样,我就可以在ArrayList上执行indexOf,然后使用该值来设置微调器中的选择。
#4
27
Based on Merrill's answer, I came up with this single line solution... it's not very pretty, but you can blame whoever maintains the code for Spinner
for neglecting to include a function that does this for that.
根据美林的回答,我想出了这个单线解决方案……它不是很漂亮,但是您可以责怪维护Spinner代码的人忽略了包含这样一个函数。
mySpinner.setSelection(((ArrayAdapter<String>)mySpinner.getAdapter()).getPosition(myString));
You'll get a warning about how the cast to a ArrayAdapter<String>
is unchecked... really, you could just use an ArrayAdapter
as Merrill did, but that just exchanges one warning for another.
您将得到一个关于如何未检查ArrayAdapter
#5
8
If you need to have an indexOf method on any old Adapter (and you don't know the underlying implementation) then you can use this:
如果您需要在任何旧适配器上使用indexOf方法(而且您不知道底层实现),那么您可以使用以下方法:
private int indexOf(final Adapter adapter, Object value)
{
for (int index = 0, count = adapter.getCount(); index < count; ++index)
{
if (adapter.getItem(index).equals(value))
{
return index;
}
}
return -1;
}
#6
8
if you are using string array this is the best way:
如果你正在使用字符串数组,这是最好的方法:
int selectionPosition= adapter.getPosition("YOUR_VALUE");
spinner.setSelection(selectionPosition);
#7
7
Based on Merrill's answer here is how to do with a CursorAdapter
根据梅里尔的回答,这里是如何使用CursorAdapter
CursorAdapter myAdapter = (CursorAdapter) spinner_listino.getAdapter(); //cast
for(int i = 0; i < myAdapter.getCount(); i++)
{
if (myAdapter.getItemId(i) == ordine.getListino() )
{
this.spinner_listino.setSelection(i);
break;
}
}
#8
7
You can use this also,
你也可以用这个,
String[] baths = getResources().getStringArray(R.array.array_baths);
mSpnBaths.setSelection(Arrays.asList(baths).indexOf(value_here));
#9
5
Use following line to select using value:
使用以下行选择使用值:
mSpinner.setSelection(yourList.indexOf("value"));
#10
3
This is my simple method to get the index by string.
这是我通过字符串获取索引的简单方法。
private int getIndexByString(Spinner spinner, String string) {
int index = 0;
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(string)) {
index = i;
break;
}
}
return index;
}
#11
2
I am using a custom adapter, for that this code is enough:
我正在使用自定义适配器,因为这段代码足够了:
yourSpinner.setSelection(arrayAdapter.getPosition("Your Desired Text"));
So, your code snippet will be like this:
因此,您的代码片段如下:
void setSpinner(String value)
{
yourSpinner.setSelection(arrayAdapter.getPosition(value));
}
#12
2
Here is how to do it if you are using a SimpleCursorAdapter
(where columnName
is the name of the db column that you used to populate your spinner
):
如果您使用的是SimpleCursorAdapter(其中columnName是用于填充您的微调器的db列的名称),那么以下是如何实现的:
private int getIndex(Spinner spinner, String columnName, String searchString) {
//Log.d(LOG_TAG, "getIndex(" + searchString + ")");
if (searchString == null || spinner.getCount() == 0) {
return -1; // Not found
}
else {
Cursor cursor = (Cursor)spinner.getItemAtPosition(0);
for (int i = 0; i < spinner.getCount(); i++) {
cursor.moveToPosition(i);
String itemText = cursor.getString(cursor.getColumnIndex(columnName));
if (itemText.equals(searchString)) {
return i;
}
}
return -1; // Not found
}
}
(Maybe you will also need to close the cursor, depending on whether you are using a loader.)
(也许您还需要关闭光标,这取决于您是否正在使用加载程序。)
Also (a refinement of Akhil's answer) this is the corresponding way to do it if you are filling your Spinner from an array:
另外(对Akhil的回答进行了改进)如果你从数组中填充微调器,这是相应的方法:
private int getIndex(Spinner spinner, String searchString) {
if (searchString == null || spinner.getCount() == 0) {
return -1; // Not found
}
else {
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).toString().equals(searchString)) {
return i; // Found!
}
}
return -1; // Not found
}
};
#13
1
here is my solution
这是我的解决方案
List<Country> list = CountryBO.GetCountries(0);
CountriesAdapter dataAdapter = new CountriesAdapter(this,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnCountries.setAdapter(dataAdapter);
spnCountries.setSelection(dataAdapter.getItemIndexById(userProfile.GetCountryId()));
and getItemIndexById below
下面getItemIndexById
public int getItemIndexById(String id) {
for (Country item : this.items) {
if(item.GetId().toString().equals(id.toString())){
return this.items.indexOf(item);
}
}
return 0;
}
Hope this help!
希望这次的帮助!
#14
0
There is actually a way to get this using an index search on the AdapterArray and all this can be done with reflection. I even went one step further as I had 10 Spinners and wanted to set them dynamically from my database and the database holds the value only not the text as the Spinner actually changes week to week so the value is my id number from the database.
实际上有一种方法可以通过在AdapterArray上进行索引搜索来实现这一点,所有这些都可以通过反射来实现。我甚至更进一步,因为我有10个旋转器,我想从数据库中动态地设置它们,数据库只保存值,而不是文本,因为旋转器每周都会改变,所以值是我的数据库id号。
// Get the JSON object from db that was saved, 10 spinner values already selected by user
JSONObject json = new JSONObject(string);
JSONArray jsonArray = json.getJSONArray("answer");
// get the current class that Spinner is called in
Class<? extends MyActivity> cls = this.getClass();
// loop through all 10 spinners and set the values with reflection
for (int j=1; j< 11; j++) {
JSONObject obj = jsonArray.getJSONObject(j-1);
String movieid = obj.getString("id");
// spinners variable names are s1,s2,s3...
Field field = cls.getDeclaredField("s"+ j);
// find the actual position of value in the list
int datapos = indexedExactSearch(Arrays.asList(Arrays.asList(this.data).toArray()), "value", movieid) ;
// find the position in the array adapter
int pos = this.adapter.getPosition(this.data[datapos]);
// the position in the array adapter
((Spinner)field.get(this)).setSelection(pos);
}
Here is the indexed search you can use on almost any list as long as the fields are on top level of object.
这里是索引搜索,只要字段位于对象的顶层,几乎可以在任何列表中使用。
/**
* Searches for exact match of the specified class field (key) value within the specified list.
* This uses a sequential search through each object in the list until a match is found or end
* of the list reached. It may be necessary to convert a list of specific objects into generics,
* ie: LinkedList<Device> needs to be passed as a List<Object> or Object[ ] by using
* Arrays.asList(device.toArray( )).
*
* @param list - list of objects to search through
* @param key - the class field containing the value
* @param value - the value to search for
* @return index of the list object with an exact match (-1 if not found)
*/
public static <T> int indexedExactSearch(List<Object> list, String key, String value) {
int low = 0;
int high = list.size()-1;
int index = low;
String val = "";
while (index <= high) {
try {
//Field[] c = list.get(index).getClass().getDeclaredFields();
val = cast(list.get(index).getClass().getDeclaredField(key).get(list.get(index)) , "NONE");
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (val.equalsIgnoreCase(value))
return index; // key found
index = index + 1;
}
return -(low + 1); // key not found return -1
}
Cast method which can be create for all primitives here is one for string and int.
可以为所有原语创建的Cast方法是用于字符串和int的。
/**
* Base String cast, return the value or default
* @param object - generic Object
* @param defaultValue - default value to give if Object is null
* @return - returns type String
*/
public static String cast(Object object, String defaultValue) {
return (object!=null) ? object.toString() : defaultValue;
}
/**
* Base integer cast, return the value or default
* @param object - generic Object
* @param defaultValue - default value to give if Object is null
* @return - returns type integer
*/
public static int cast(Object object, int defaultValue) {
return castImpl(object, defaultValue).intValue();
}
/**
* Base cast, return either the value or the default
* @param object - generic Object
* @param defaultValue - default value to give if Object is null
* @return - returns type Object
*/
public static Object castImpl(Object object, Object defaultValue) {
return object!=null ? object : defaultValue;
}
#15
0
To make the application remember the last selected spinner values, you can use below code:
要使应用程序记住最后选定的微调控制项的值,可以使用以下代码:
-
Below code reads the spinner value and sets the spinner position accordingly.
下面的代码读取spinner值并相应地设置spinner位置。
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); int spinnerPosition; Spinner spinner1 = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource( this, R.array.ccy_array, android.R.layout.simple_spinner_dropdown_item); adapter1.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); // Apply the adapter to the spinner spinner1.setAdapter(adapter1); // changes to remember last spinner position spinnerPosition = 0; String strpos1 = prfs.getString("SPINNER1_VALUE", ""); if (strpos1 != null || !strpos1.equals(null) || !strpos1.equals("")) { strpos1 = prfs.getString("SPINNER1_VALUE", ""); spinnerPosition = adapter1.getPosition(strpos1); spinner1.setSelection(spinnerPosition); spinnerPosition = 0; }
-
And put below code where you know latest spinner values are present, or somewhere else as required. This piece of code basically writes the spinner value in SharedPreferences.
并将代码放在您知道最近的微调值存在的地方,或者其他需要的地方。这段代码主要在SharedPreferences中写入微调值。
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1); String spinlong1 = spinner1.getSelectedItem().toString(); SharedPreferences prfs = getSharedPreferences("WHATEVER", Context.MODE_PRIVATE); SharedPreferences.Editor editor = prfs.edit(); editor.putString("SPINNER1_VALUE", spinlong1); editor.commit();
#16
0
I had the same issue when trying to select the correct item in a spinner populated using a cursorLoader. I retrieved the id of the item I wanted to select first from table 1 and then used a CursorLoader to populate the spinner. In the onLoadFinished I cycled through the cursor populating the spinner's adapter until I found the item that matched the id I already had. Then assigned the row number of the cursor to the spinner's selected position. It would be nice to have a similar function to pass in the id of the value you wish to select in the spinner when populating details on a form containing saved spinner results.
在使用cursorLoader填充微调器时,我也遇到了同样的问题。我检索了要从表1中首先选择的项目的id,然后使用CursorLoader填充微调器。在onLoadFinished中,我循环遍历了填充spinner适配器的游标,直到找到匹配我已经拥有的id的项。然后将光标的行号分配给spinner的选定位置。当在包含已保存的微调控制项结果的窗体上填充细节时,使用类似的函数来传递您希望在微调控制项中选择的值的id,这将是很好的。
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.swapCursor(cursor);
cursor.moveToFirst();
int row_count = 0;
int spinner_row = 0;
while (spinner_row < 0 || row_count < cursor.getCount()){ // loop until end of cursor or the
// ID is found
int cursorItemID = bCursor.getInt(cursor.getColumnIndexOrThrow(someTable.COLUMN_ID));
if (knownID==cursorItemID){
spinner_row = row_count; //set the spinner row value to the same value as the cursor row
}
cursor.moveToNext();
row_count++;
}
}
spinner.setSelection(spinner_row ); //set the selected item in the spinner
}
#17
0
As some of the previous answers are very right, I just want to make sure from none of you fall in such this problem.
由于前面的一些答案是非常正确的,我只想确保你们没有人陷入这样的问题。
If you set the values to the ArrayList
using String.format
, you MUST get the position of the value using the same string structure String.format
.
如果您使用字符串将值设置为ArrayList。格式,您必须使用相同的字符串结构string .format获取值的位置。
An example:
一个例子:
ArrayList<String> myList = new ArrayList<>();
myList.add(String.format(Locale.getDefault() ,"%d", 30));
myList.add(String.format(Locale.getDefault(), "%d", 50));
myList.add(String.format(Locale.getDefault(), "%d", 70));
myList.add(String.format(Locale.getDefault(), "%d", 100));
You must get the position of needed value like this:
你必须得到所需价值的位置,如:
myList.setSelection(myAdapter.getPosition(String.format(Locale.getDefault(), "%d", 70)));
Otherwise, you'll get the -1
, item not found!
否则,您将得到-1,未找到的项!
I used Locale.getDefault()
because of Arabic language.
由于使用阿拉伯语,我使用了Locale.getDefault()。
I hope that will be helpful for you.
我希望这对你有帮助。
#18
0
Here is my hopefully complete solution. I have following enum:
这是我希望完整的解。我有下面的枚举:
public enum HTTPMethod {GET, HEAD}
used in following class
用于以下类
public class WebAddressRecord {
...
public HTTPMethod AccessMethod = HTTPMethod.HEAD;
...
Code to set the spinner by HTTPMethod enum-member:
通过HTTPMethod enum-member设置spinner的代码:
Spinner mySpinner = (Spinner) findViewById(R.id.spinnerHttpmethod);
ArrayAdapter<HTTPMethod> adapter = new ArrayAdapter<HTTPMethod>(this, android.R.layout.simple_spinner_item, HTTPMethod.values());
mySpinner.setAdapter(adapter);
int selectionPosition= adapter.getPosition(webAddressRecord.AccessMethod);
mySpinner.setSelection(selectionPosition);
Where R.id.spinnerHttpmethod
is defined in a layout-file, and android.R.layout.simple_spinner_item
is delivered by android-studio.
R.id的地方。spinnerHttpmethod在一个布图文件和android.R.layout中定义。simple_spinner_item由android-studio交付。
#19
0
YourAdapter yourAdapter =
new YourAdapter (getActivity(),
R.layout.list_view_item,arrData);
yourAdapter .setDropDownViewResource(R.layout.list_view_item);
mySpinner.setAdapter(yourAdapter );
String strCompare = "Indonesia";
for (int i = 0; i < arrData.length ; i++){
if(arrData[i].getCode().equalsIgnoreCase(strCompare)){
int spinnerPosition = yourAdapter.getPosition(arrData[i]);
mySpinner.setSelection(spinnerPosition);
}
}
#20
0
simply call
简单的电话
int Pos = country_Adapter.getPosition(user.getStateName()); spinnerCountry.selectItem(Pos);
int Pos = country_Adapter.getPosition(user.getStateName());spinnerCountry.selectItem(Pos);
#21
-3
you have to pass your custom adapter with position like REPEAT[position]. and it works properly.
您必须传递自定义适配器的位置,比如REPEAT[position]。它能正常工作。
#1
534
Suppose your Spinner
is named mSpinner
, and it contains as one of its choices: "some value".
假设您的Spinner被命名为mSpinner,它包含了它的一个选择:“一些值”。
To find and compare the position of "some value" in the Spinner use this:
为了找到并比较“某些值”在纺纱器中的位置,使用以下方法:
String compareValue = "some value";
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
if (compareValue != null) {
int spinnerPosition = adapter.getPosition(compareValue);
mSpinner.setSelection(spinnerPosition);
}
#2
105
A simple way to set spinner based on value is
一种基于值设置微调控制项的简单方法是
mySpinner.setSelection(getIndex(mySpinner, myValue));
//private method of your class
private int getIndex(Spinner spinner, String myString){
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)){
return i;
}
}
return 0;
}
Way to complex code are already there, this is just much plainer.
到复杂代码的方法已经在那里了,这是非常简单的。
#3
34
I keep a separate ArrayList of all the items in my Spinners. This way I can do indexOf on the ArrayList and then use that value to set the selection in the Spinner.
我在我的旋转器中保存了一个单独的数组列表。这样,我就可以在ArrayList上执行indexOf,然后使用该值来设置微调器中的选择。
#4
27
Based on Merrill's answer, I came up with this single line solution... it's not very pretty, but you can blame whoever maintains the code for Spinner
for neglecting to include a function that does this for that.
根据美林的回答,我想出了这个单线解决方案……它不是很漂亮,但是您可以责怪维护Spinner代码的人忽略了包含这样一个函数。
mySpinner.setSelection(((ArrayAdapter<String>)mySpinner.getAdapter()).getPosition(myString));
You'll get a warning about how the cast to a ArrayAdapter<String>
is unchecked... really, you could just use an ArrayAdapter
as Merrill did, but that just exchanges one warning for another.
您将得到一个关于如何未检查ArrayAdapter
#5
8
If you need to have an indexOf method on any old Adapter (and you don't know the underlying implementation) then you can use this:
如果您需要在任何旧适配器上使用indexOf方法(而且您不知道底层实现),那么您可以使用以下方法:
private int indexOf(final Adapter adapter, Object value)
{
for (int index = 0, count = adapter.getCount(); index < count; ++index)
{
if (adapter.getItem(index).equals(value))
{
return index;
}
}
return -1;
}
#6
8
if you are using string array this is the best way:
如果你正在使用字符串数组,这是最好的方法:
int selectionPosition= adapter.getPosition("YOUR_VALUE");
spinner.setSelection(selectionPosition);
#7
7
Based on Merrill's answer here is how to do with a CursorAdapter
根据梅里尔的回答,这里是如何使用CursorAdapter
CursorAdapter myAdapter = (CursorAdapter) spinner_listino.getAdapter(); //cast
for(int i = 0; i < myAdapter.getCount(); i++)
{
if (myAdapter.getItemId(i) == ordine.getListino() )
{
this.spinner_listino.setSelection(i);
break;
}
}
#8
7
You can use this also,
你也可以用这个,
String[] baths = getResources().getStringArray(R.array.array_baths);
mSpnBaths.setSelection(Arrays.asList(baths).indexOf(value_here));
#9
5
Use following line to select using value:
使用以下行选择使用值:
mSpinner.setSelection(yourList.indexOf("value"));
#10
3
This is my simple method to get the index by string.
这是我通过字符串获取索引的简单方法。
private int getIndexByString(Spinner spinner, String string) {
int index = 0;
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(string)) {
index = i;
break;
}
}
return index;
}
#11
2
I am using a custom adapter, for that this code is enough:
我正在使用自定义适配器,因为这段代码足够了:
yourSpinner.setSelection(arrayAdapter.getPosition("Your Desired Text"));
So, your code snippet will be like this:
因此,您的代码片段如下:
void setSpinner(String value)
{
yourSpinner.setSelection(arrayAdapter.getPosition(value));
}
#12
2
Here is how to do it if you are using a SimpleCursorAdapter
(where columnName
is the name of the db column that you used to populate your spinner
):
如果您使用的是SimpleCursorAdapter(其中columnName是用于填充您的微调器的db列的名称),那么以下是如何实现的:
private int getIndex(Spinner spinner, String columnName, String searchString) {
//Log.d(LOG_TAG, "getIndex(" + searchString + ")");
if (searchString == null || spinner.getCount() == 0) {
return -1; // Not found
}
else {
Cursor cursor = (Cursor)spinner.getItemAtPosition(0);
for (int i = 0; i < spinner.getCount(); i++) {
cursor.moveToPosition(i);
String itemText = cursor.getString(cursor.getColumnIndex(columnName));
if (itemText.equals(searchString)) {
return i;
}
}
return -1; // Not found
}
}
(Maybe you will also need to close the cursor, depending on whether you are using a loader.)
(也许您还需要关闭光标,这取决于您是否正在使用加载程序。)
Also (a refinement of Akhil's answer) this is the corresponding way to do it if you are filling your Spinner from an array:
另外(对Akhil的回答进行了改进)如果你从数组中填充微调器,这是相应的方法:
private int getIndex(Spinner spinner, String searchString) {
if (searchString == null || spinner.getCount() == 0) {
return -1; // Not found
}
else {
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).toString().equals(searchString)) {
return i; // Found!
}
}
return -1; // Not found
}
};
#13
1
here is my solution
这是我的解决方案
List<Country> list = CountryBO.GetCountries(0);
CountriesAdapter dataAdapter = new CountriesAdapter(this,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnCountries.setAdapter(dataAdapter);
spnCountries.setSelection(dataAdapter.getItemIndexById(userProfile.GetCountryId()));
and getItemIndexById below
下面getItemIndexById
public int getItemIndexById(String id) {
for (Country item : this.items) {
if(item.GetId().toString().equals(id.toString())){
return this.items.indexOf(item);
}
}
return 0;
}
Hope this help!
希望这次的帮助!
#14
0
There is actually a way to get this using an index search on the AdapterArray and all this can be done with reflection. I even went one step further as I had 10 Spinners and wanted to set them dynamically from my database and the database holds the value only not the text as the Spinner actually changes week to week so the value is my id number from the database.
实际上有一种方法可以通过在AdapterArray上进行索引搜索来实现这一点,所有这些都可以通过反射来实现。我甚至更进一步,因为我有10个旋转器,我想从数据库中动态地设置它们,数据库只保存值,而不是文本,因为旋转器每周都会改变,所以值是我的数据库id号。
// Get the JSON object from db that was saved, 10 spinner values already selected by user
JSONObject json = new JSONObject(string);
JSONArray jsonArray = json.getJSONArray("answer");
// get the current class that Spinner is called in
Class<? extends MyActivity> cls = this.getClass();
// loop through all 10 spinners and set the values with reflection
for (int j=1; j< 11; j++) {
JSONObject obj = jsonArray.getJSONObject(j-1);
String movieid = obj.getString("id");
// spinners variable names are s1,s2,s3...
Field field = cls.getDeclaredField("s"+ j);
// find the actual position of value in the list
int datapos = indexedExactSearch(Arrays.asList(Arrays.asList(this.data).toArray()), "value", movieid) ;
// find the position in the array adapter
int pos = this.adapter.getPosition(this.data[datapos]);
// the position in the array adapter
((Spinner)field.get(this)).setSelection(pos);
}
Here is the indexed search you can use on almost any list as long as the fields are on top level of object.
这里是索引搜索,只要字段位于对象的顶层,几乎可以在任何列表中使用。
/**
* Searches for exact match of the specified class field (key) value within the specified list.
* This uses a sequential search through each object in the list until a match is found or end
* of the list reached. It may be necessary to convert a list of specific objects into generics,
* ie: LinkedList<Device> needs to be passed as a List<Object> or Object[ ] by using
* Arrays.asList(device.toArray( )).
*
* @param list - list of objects to search through
* @param key - the class field containing the value
* @param value - the value to search for
* @return index of the list object with an exact match (-1 if not found)
*/
public static <T> int indexedExactSearch(List<Object> list, String key, String value) {
int low = 0;
int high = list.size()-1;
int index = low;
String val = "";
while (index <= high) {
try {
//Field[] c = list.get(index).getClass().getDeclaredFields();
val = cast(list.get(index).getClass().getDeclaredField(key).get(list.get(index)) , "NONE");
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (val.equalsIgnoreCase(value))
return index; // key found
index = index + 1;
}
return -(low + 1); // key not found return -1
}
Cast method which can be create for all primitives here is one for string and int.
可以为所有原语创建的Cast方法是用于字符串和int的。
/**
* Base String cast, return the value or default
* @param object - generic Object
* @param defaultValue - default value to give if Object is null
* @return - returns type String
*/
public static String cast(Object object, String defaultValue) {
return (object!=null) ? object.toString() : defaultValue;
}
/**
* Base integer cast, return the value or default
* @param object - generic Object
* @param defaultValue - default value to give if Object is null
* @return - returns type integer
*/
public static int cast(Object object, int defaultValue) {
return castImpl(object, defaultValue).intValue();
}
/**
* Base cast, return either the value or the default
* @param object - generic Object
* @param defaultValue - default value to give if Object is null
* @return - returns type Object
*/
public static Object castImpl(Object object, Object defaultValue) {
return object!=null ? object : defaultValue;
}
#15
0
To make the application remember the last selected spinner values, you can use below code:
要使应用程序记住最后选定的微调控制项的值,可以使用以下代码:
-
Below code reads the spinner value and sets the spinner position accordingly.
下面的代码读取spinner值并相应地设置spinner位置。
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); int spinnerPosition; Spinner spinner1 = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource( this, R.array.ccy_array, android.R.layout.simple_spinner_dropdown_item); adapter1.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); // Apply the adapter to the spinner spinner1.setAdapter(adapter1); // changes to remember last spinner position spinnerPosition = 0; String strpos1 = prfs.getString("SPINNER1_VALUE", ""); if (strpos1 != null || !strpos1.equals(null) || !strpos1.equals("")) { strpos1 = prfs.getString("SPINNER1_VALUE", ""); spinnerPosition = adapter1.getPosition(strpos1); spinner1.setSelection(spinnerPosition); spinnerPosition = 0; }
-
And put below code where you know latest spinner values are present, or somewhere else as required. This piece of code basically writes the spinner value in SharedPreferences.
并将代码放在您知道最近的微调值存在的地方,或者其他需要的地方。这段代码主要在SharedPreferences中写入微调值。
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1); String spinlong1 = spinner1.getSelectedItem().toString(); SharedPreferences prfs = getSharedPreferences("WHATEVER", Context.MODE_PRIVATE); SharedPreferences.Editor editor = prfs.edit(); editor.putString("SPINNER1_VALUE", spinlong1); editor.commit();
#16
0
I had the same issue when trying to select the correct item in a spinner populated using a cursorLoader. I retrieved the id of the item I wanted to select first from table 1 and then used a CursorLoader to populate the spinner. In the onLoadFinished I cycled through the cursor populating the spinner's adapter until I found the item that matched the id I already had. Then assigned the row number of the cursor to the spinner's selected position. It would be nice to have a similar function to pass in the id of the value you wish to select in the spinner when populating details on a form containing saved spinner results.
在使用cursorLoader填充微调器时,我也遇到了同样的问题。我检索了要从表1中首先选择的项目的id,然后使用CursorLoader填充微调器。在onLoadFinished中,我循环遍历了填充spinner适配器的游标,直到找到匹配我已经拥有的id的项。然后将光标的行号分配给spinner的选定位置。当在包含已保存的微调控制项结果的窗体上填充细节时,使用类似的函数来传递您希望在微调控制项中选择的值的id,这将是很好的。
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.swapCursor(cursor);
cursor.moveToFirst();
int row_count = 0;
int spinner_row = 0;
while (spinner_row < 0 || row_count < cursor.getCount()){ // loop until end of cursor or the
// ID is found
int cursorItemID = bCursor.getInt(cursor.getColumnIndexOrThrow(someTable.COLUMN_ID));
if (knownID==cursorItemID){
spinner_row = row_count; //set the spinner row value to the same value as the cursor row
}
cursor.moveToNext();
row_count++;
}
}
spinner.setSelection(spinner_row ); //set the selected item in the spinner
}
#17
0
As some of the previous answers are very right, I just want to make sure from none of you fall in such this problem.
由于前面的一些答案是非常正确的,我只想确保你们没有人陷入这样的问题。
If you set the values to the ArrayList
using String.format
, you MUST get the position of the value using the same string structure String.format
.
如果您使用字符串将值设置为ArrayList。格式,您必须使用相同的字符串结构string .format获取值的位置。
An example:
一个例子:
ArrayList<String> myList = new ArrayList<>();
myList.add(String.format(Locale.getDefault() ,"%d", 30));
myList.add(String.format(Locale.getDefault(), "%d", 50));
myList.add(String.format(Locale.getDefault(), "%d", 70));
myList.add(String.format(Locale.getDefault(), "%d", 100));
You must get the position of needed value like this:
你必须得到所需价值的位置,如:
myList.setSelection(myAdapter.getPosition(String.format(Locale.getDefault(), "%d", 70)));
Otherwise, you'll get the -1
, item not found!
否则,您将得到-1,未找到的项!
I used Locale.getDefault()
because of Arabic language.
由于使用阿拉伯语,我使用了Locale.getDefault()。
I hope that will be helpful for you.
我希望这对你有帮助。
#18
0
Here is my hopefully complete solution. I have following enum:
这是我希望完整的解。我有下面的枚举:
public enum HTTPMethod {GET, HEAD}
used in following class
用于以下类
public class WebAddressRecord {
...
public HTTPMethod AccessMethod = HTTPMethod.HEAD;
...
Code to set the spinner by HTTPMethod enum-member:
通过HTTPMethod enum-member设置spinner的代码:
Spinner mySpinner = (Spinner) findViewById(R.id.spinnerHttpmethod);
ArrayAdapter<HTTPMethod> adapter = new ArrayAdapter<HTTPMethod>(this, android.R.layout.simple_spinner_item, HTTPMethod.values());
mySpinner.setAdapter(adapter);
int selectionPosition= adapter.getPosition(webAddressRecord.AccessMethod);
mySpinner.setSelection(selectionPosition);
Where R.id.spinnerHttpmethod
is defined in a layout-file, and android.R.layout.simple_spinner_item
is delivered by android-studio.
R.id的地方。spinnerHttpmethod在一个布图文件和android.R.layout中定义。simple_spinner_item由android-studio交付。
#19
0
YourAdapter yourAdapter =
new YourAdapter (getActivity(),
R.layout.list_view_item,arrData);
yourAdapter .setDropDownViewResource(R.layout.list_view_item);
mySpinner.setAdapter(yourAdapter );
String strCompare = "Indonesia";
for (int i = 0; i < arrData.length ; i++){
if(arrData[i].getCode().equalsIgnoreCase(strCompare)){
int spinnerPosition = yourAdapter.getPosition(arrData[i]);
mySpinner.setSelection(spinnerPosition);
}
}
#20
0
simply call
简单的电话
int Pos = country_Adapter.getPosition(user.getStateName()); spinnerCountry.selectItem(Pos);
int Pos = country_Adapter.getPosition(user.getStateName());spinnerCountry.selectItem(Pos);
#21
-3
you have to pass your custom adapter with position like REPEAT[position]. and it works properly.
您必须传递自定义适配器的位置,比如REPEAT[position]。它能正常工作。