Spinner のデータベースに保存されている値を事前に選択する必要がある更新ビューがあります。
このようなことを念頭に置いていましたが、方法Adapter
がないindexOf
ため、行き詰まっています。
void setSpinner(String value)
{
int pos = getSpinnerField().getAdapter().indexOf(value);
getSpinnerField().setSelection(pos);
}
your のSpinner
名前がmSpinner
で、選択肢の 1 つとして「some value」が含まれているとします。
スピナーで「何らかの値」の位置を見つけて比較するには、次を使用します。
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);
}
メリルの答えに基づいて、私はこの単一行の解決策を思いつきました...それはあまりきれいではありませんが、コードを維持している人は誰でも、そのSpinner
ためにこれを行う関数を含めることを怠ったことを非難できます。
mySpinner.setSelection(((ArrayAdapter<String>)mySpinner.getAdapter()).getPosition(myString));
a へのキャストがどのようにArrayAdapter<String>
チェックされていないかについて警告が表示されます...実際には、メリルが行ったように an を使用できますがArrayAdapter
、それはある警告を別の警告と交換するだけです。
警告が問題を引き起こす場合は、追加するだけです
@SuppressWarnings("unchecked")
メソッド署名またはステートメントの上。
スピナー内のすべてのアイテムの個別のArrayListを保持しています。このようにして、ArrayListでindexOfを実行し、その値を使用してスピナーで選択を設定できます。
文字列配列を使用している場合、これが最善の方法です。
int selectionPosition= adapter.getPosition("YOUR_VALUE");
spinner.setSelection(selectionPosition);
次の行を使用して、値を使用して選択します。
mSpinner.setSelection(yourList.indexOf("value"));
これも使えますが、
String[] baths = getResources().getStringArray(R.array.array_baths);
mSpnBaths.setSelection(Arrays.asList(baths).indexOf(value_here));
古い Adapter に 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;
}
}
ここに私の解決策があります
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;
}
この助けを願っています!
このコードで十分なため、カスタムアダプターを使用しています:
yourSpinner.setSelection(arrayAdapter.getPosition("Your Desired Text"));
したがって、コード スニペットは次のようになります。
void setSpinner(String value)
{
yourSpinner.setSelection(arrayAdapter.getPosition(value));
}
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<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
}
ここですべてのプリミティブに対して作成できるキャスト メソッドは、string と int の 1 つです。
/**
* 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;
}
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
}
これが私のうまくいけば完全な解決策です。私は次の列挙型を持っています:
public enum HTTPMethod {GET, HEAD}
次のクラスで使用
public class WebAddressRecord {
...
public HTTPMethod AccessMethod = HTTPMethod.HEAD;
...
HTTPMethod enum-member でスピナーを設定するコード:
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);
whereR.id.spinnerHttpmethod
はレイアウト ファイルで定義され、android.R.layout.simple_spinner_item
android-studio によって提供されます。
Localizationでも機能する何かが必要だったので、次の 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();
}