如何按值而不是按位置设置微调器的选定项?

问题描述 投票:267回答:24

我有一个更新视图,我需要为Spinner预先选择存储在数据库中的值。

我记得这样的事情,但Adapter没有indexOf方法,所以我被卡住了。

void setSpinner(String value)
{
    int pos = getSpinnerField().getAdapter().indexOf(value);
    getSpinnerField().setSelection(pos);
}
java android adapter spinner
24个回答
604
投票

假设你的Spinner被命名为mSpinner,它包含了一个选择:“some value”。

要查找和比较Spinner中“某些值”的位置,请使用以下命令:

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);
}

3
投票

这是我通过字符串获取索引的简单方法。

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;
}

2
投票

我正在使用自定义适配器,因为这个代码足够了:

yourSpinner.setSelection(arrayAdapter.getPosition("Your Desired Text"));

所以,你的代码片段将是这样的:

void setSpinner(String value)
    {
         yourSpinner.setSelection(arrayAdapter.getPosition(value));
    }

2
投票

如果您使用SimpleCursorAdapter(其中columnName是您用来填充spinner的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
    }
}

(也许您还需要关闭光标,具体取决于您是否使用了加载程序。)

另外(Akhil's answer的一个改进)如果你从一个数组填充你的Spinner,这是相应的方法:

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
    }
};

1
投票

这是我的解决方案

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()));

和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;
}

希望这有帮助!


1
投票

如果在XML布局中将XML数组设置为微调器,则可以执行此操作

final Spinner hr = v.findViewById(R.id.chr);
final String[] hrs = getResources().getStringArray(R.array.hours);
if(myvalue!=null){
   for (int x = 0;x< hrs.length;x++){
      if(myvalue.equals(hrs[x])){
         hr.setSelection(x);
      }
   }
}

0
投票

实际上有一种方法可以使用AdapterArray上的索引搜索来实现这一点,所有这些都可以通过反射完成。我甚至更进一步,因为我有10个Spinners,并且想要从我的数据库中动态设置它们,并且数据库只保留值而不是文本,因为Spinner实际上每周都会更改,因此值是数据库中的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);

}

只要字段位于对象的顶层,您就可以在几乎任何列表中使用索引搜索。

    /**
 * 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&ltDevice&gt needs to be passed as a List&ltObject&gt or Object[&nbsp] by using 
 * Arrays.asList(device.toArray(&nbsp)).
 * 
 * @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方法是一个用于string和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;
}

0
投票

要使应用程序记住最后选择的微调器值,您可以使用以下代码:

  1. 下面的代码读取微调器值并相应地设置微调器位置。 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; }
  2. 并将下面的代码放在您知道最新的微调器值的位置,或者根据需要放在其他位置。这段代码基本上将微调器值写在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();

0
投票

尝试在使用cursorLoader填充的微调器中选择正确的项时,我遇到了同样的问题。我从表1中检索了我想要选择的项的id,然后使用CursorLoader填充微调器。在onLoadFinished我循环通过光标填充微调器的适配器,直到我找到与我已经拥有的id匹配的项目。然后将光标的行号分配给微调器的选定位置。当在包含已保存的微调器结果的表单上填充详细信息时,使用类似的函数传递要在微调器中选择的值的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

}

0
投票

由于以前的一些答案是非常正确的,我只想确保你们都没有陷入这样的问题。

如果使用ArrayList将值设置为String.format,则必须使用相同的字符串结构String.format获取值的位置。

一个例子:

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));

你必须得到所需价值的位置,如下所示:

myList.setSelection(myAdapter.getPosition(String.format(Locale.getDefault(), "%d", 70)));

否则,你会得到-1,找不到项目!

因为阿拉伯语,我使用了Locale.getDefault()

我希望这对你有所帮助。


0
投票

这是我希望完整的解决方案。我有以下枚举:

public enum HTTPMethod {GET, HEAD}

用于下面的课程

public class WebAddressRecord {
...
public HTTPMethod AccessMethod = HTTPMethod.HEAD;
...

通过HTTPMethod枚举成员设置微调器的代码:

    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);

其中R.id.spinnerHttpmethod在布局文件中定义,而android.R.layout.simple_spinner_item由android-studio提供。


127
投票

一种基于值设置微调器的简单方法是

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;
 } 

复杂代码的方法已经存在,这只是更简单。


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);
        }
    }

0
投票

非常简单只需使用getSelectedItem();

例如:

ArrayAdapter<CharSequence> type=ArrayAdapter.createFromResource(this,R.array.admin_typee,android.R.layout.simple_spinner_dropdown_item);
        type.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mainType.setAdapter(type);

String group=mainType.getSelectedItem().toString();

上面的方法返回一个字符串值

在上面,R.array.admin_type是值中的字符串资源文件

只需在值>>字符串中创建一个.xml文件


0
投票

假设您需要从资源中填充字符串数组中的微调器,并且您希望保持从服务器中选择值。因此,这是在微调器中设置从服务器中选择值的一种方法。

pincodeSpinner.setSelection(resources.getStringArray(R.array.pincodes).indexOf(javaObject.pincode))

希望能帮助到你!附:代码在Kotlin!


0
投票

既然我需要一些东西,那也适用于Localization,我提出了这两种方法:

    private int getArrayPositionForValue(final int arrayResId, final String value) {
        final Resources english = Utils.getLocalizedResources(this, new Locale("en"));
        final List<String> arrayValues = Arrays.asList(english.getStringArray(arrayResId));

        for (int position = 0; position < arrayValues.size(); position++) {
            if (arrayValues.get(position).equalsIgnoreCase(value)) {
                return position;
            }
        }
        Log.w(TAG, "getArrayPosition() --> return 0 (fallback); No index found for value = " + value);
        return 0;
    }

正如您所看到的,我还发现了在array.xml和我正在比较的value之间的区分大小写的复杂性。如果你没有这个,上面的方法可以简化为:

return arrayValues.indexOf(value);

静态辅助方法

public static Resources getLocalizedResources(Context context, Locale desiredLocale) {
        Configuration conf = context.getResources().getConfiguration();
        conf = new Configuration(conf);
        conf.setLocale(desiredLocale);
        Context localizedContext = context.createConfigurationContext(conf);
        return localizedContext.getResources();
    }

-3
投票

你必须通过像REPEAT [position]这样的位置传递自定义适配器。它运作正常。


34
投票

我保留了Spinners中所有项目的单独ArrayList。这样我可以在ArrayList上执行indexOf,然后使用该值在Spinner中设置选择。


28
投票

基于Merrill's answer,我提出了这个单行解决方案...它不是很漂亮,但你可以责怪谁维护Spinner的代码忽略了包含一个为此做到这一点的函数。

mySpinner.setSelection(((ArrayAdapter<String>)mySpinner.getAdapter()).getPosition(myString));

你会得到一个关于如何取消选中ArrayAdapter<String>的演员的警告......真的,你可以像Merrill那样使用ArrayAdapter,但这只是为另一个警告交换一个警告。


10
投票

如果你使用字符串数组这是最好的方法:

int selectionPosition= adapter.getPosition("YOUR_VALUE");
spinner.setSelection(selectionPosition);

8
投票

如果您需要在任何旧适配器上使用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;
}

8
投票

你也可以用它,

String[] baths = getResources().getStringArray(R.array.array_baths);
mSpnBaths.setSelection(Arrays.asList(baths).indexOf(value_here));

7
投票

根据Merrill的回答,这里是如何处理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;
        }
    }

5
投票

使用以下行选择使用值:

mSpinner.setSelection(yourList.indexOf("value"));
© www.soinside.com 2019 - 2024. All rights reserved.