スピナーの選択項目を位置ではなく値で設定するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/2390102

  •  24-09-2019
  •  | 
  •  

質問

更新ビューがあり、スピナーのデータベースに保存されている値を事前に選択する必要があります。

こんなことを念頭に置いていたのですが、 Adapter ありません indexOf 方法なので、行き詰まっています。

void setSpinner(String value)
{
    int pos = getSpinnerField().getAdapter().indexOf(value);
    getSpinnerField().setSelection(pos);
}
役に立ちましたか?

解決

あなたのSpinnermSpinnerという名前、そしてそれはその選択肢の一つとして含まれているとします。「何らかの値」

これを使用して検索し、スピナーで「何らかの値」の位置を比較するには:

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

他のヒント

の値に基づいてセットスピナーする簡単な方法は、

であります
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;
 } 

は既に存在している複雑なコードへの道は、これはただずっと地味です。

私は私のスピナー内のすべての項目を個別のArrayListを保ちます。私は、ArrayListの上のindexOfを行うことができ、この方法は、スピナーで選択を設定し、その値を使用します。

メリルの回答するに基づいて

、私はこの一行の解決策を考え出した...それは非常にきれいではありませんが、あなたそのためにこれを行う機能が含まれるように無視のためのSpinnerためのコードを保持誰でも非難することができます。

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

あなたはArrayAdapter<String>へのキャストがオフになっているかについての警告を得るでしょう...本当に、あなただけのメリルが行ったようにArrayAdapterを使用しますが、別のためだけの交換1つの警告ことができます。

:あなたは文字列配列を使用している場合は、

これが最善の方法です

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

また、これを使用することができ、

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

あなたは(あなたが基本となる実装を知らない)、あなたはこれを使用することができます任意の古いアダプタ上の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;
}

メリルの答えに基づいて、 ここで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;
        }
    }

を使用する次の行値を使用して選択します:

mSpinner.setSelection(yourList.indexOf("value"));

これは文字列でインデックスを取得するために私の簡単な方法です。

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

私はこのコードが十分であることのために、カスタムアダプタを使用しています:

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

だから、あなたのコードスニペットは次のようになります:

void setSpinner(String value)
    {
         yourSpinner.setSelection(arrayAdapter.getPosition(value));
    }
ここでは、(SimpleCursorAdapterはあなたのcolumnNameを移入するために使用したDBの列の名前です)spinnerを使用している場合は、それを行う方法です。

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

(たぶん、あなたはまた、あなたがローダーを使用しているかどうかに応じて、カーソルをクローズする必要があります。)

また、(アクヒルの答えでの改良は)これはあなたからあなたのスピナーを満たしている場合は、それを行うには、対応する方法があります配列ます:

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

ここに私の解決策がある。

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

・ホープこのヘルプ!

あなたは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);
      }
   }
}
あり、実際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);

}
ここでは、長いフィールドは、オブジェクトのトップレベルにあるようとして、ほぼすべてのリストを上使用することができ、検索インデックスが作成されます。

    /**
 * 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
}

ここでは、すべてのプリミティブのために作成することができますキャストの方法は、文字列と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;
}

最後に選択したスピナーの値をアプリケーションに記憶させるには、以下のコードを使用できます。

  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();
    
cursorLoaderを使用して人口スピナーで正しい項目を選択しようとすると、

私は同じ問題がありました。私は、表1からの第1の選択したかったアイテムのIDを取得した後、スピナーを移入するCursorLoaderを使用します。私はすでに持っていたIDと一致したことを項目を見つけるまでonLoadFinished Iでスピナーのアダプタを取り込むカーソルを循環。次いで、スピナーの選択された位置にカーソルの行番号を割り当てます。保存されたスピナー結果を含むフォームの詳細を取り込むときに、スピナーで選択したい値の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

}

前の回答の一部として非常に右、私はちょうどあなたのどれから確認するされているが、このような問題に落ちます。

あなたが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()を使用の。

私はそれがあなたのために役立つことを願っています。

ここに私うまくいけば、完全なソリューションです。私は列挙型を次ています:

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がアンドロイド・スタジオで配信されます。

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

非常に単純なだけ使用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ファイルを作成し、文字列

あなたは、リソースから文字列の配列からスピナーを埋めるために必要があると、あなたは、サーバーから値を選択した状態を維持したいです。 だから、これは一つの方法スピナーにサーバーから値を選択して設定することです。

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

希望、それが役立ちます! 後記コードKotlinである!

私ものローカライズので動作することを何かを、必要なので、

、私はこれらの2つの方法を思い付います:

    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;
    }
あなたが見ることができるように

、私はまたarrays.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();
    }

あなたはちょうどあなたのコードはよりシンプルで、より明確に、この方法を使用することができます。

ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinnerCountry.getAdapter();
int position = adapter.getPosition(obj.getCountry());
spinnerCountry.setSelection(position);

希望、それは助けています。

あなたはREPEAT [位置]のような位置にカスタムアダプタを渡す必要があります。それが正常に動作します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top