Spinner의 선택한 항목을 위치가 아닌 값으로 설정하는 방법은 무엇입니까?
Spinner에 대해 데이터베이스에 저장된 값을 미리 선택해야 하는 업데이트 보기가 있습니다.
이런 생각을 하고 있었는데AdapterindexOf방법이 있어서 꼼짝도 못해요
void setSpinner(String value)
{
int pos = getSpinnerField().getAdapter().indexOf(value);
getSpinnerField().setSelection(pos);
}
예를 들어 다음과 같습니다.Spinner 붙여지다mSpinner「일부 가치」라고 하는 선택지가 포함되어 있습니다.
스피너에서 "일부 값"의 위치를 찾아 비교하려면 다음을 사용합니다.
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;
}
복잡한 코드로 가는 방법은 이미 존재합니다. 이것은 훨씬 더 간단합니다.
메릴의 대답에 근거해, 나는 이 하나의 해결책을 생각해냈다...별로 예쁘진 않지만 코드를 유지하는 사람은Spinner이 기능을 포함시키지 않은 것에 대한 책임입니다.
mySpinner.setSelection(((ArrayAdapter<String>)mySpinner.getAdapter()).getPosition(myString));
ArrayAdapter<String>★★★★★★★★★★… 그냥 말 an an, an an an an an ...ArrayAdapter메릴이 그랬던 것처럼, 하지만 그것은 하나의 경고와 다른 경고로 교환될 뿐이다.
경고로 인해 문제가 발생할 경우,
@SuppressWarnings("unchecked")
메서드 시그니처 또는 스테이트먼트 위에 표시됩니다.
Spinner에 있는 모든 아이템의 Array List를 별도로 보관하고 있습니다.이렇게 하면 ArrayList에서 indexOf를 수행한 후 이 값을 사용하여 Spinner에서 선택 항목을 설정할 수 있습니다.
문자열 배열을 사용하는 경우 다음 방법이 가장 좋습니다.
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));
이전 어댑터에서 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;
}
여기 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;
}
}
이 방법을 사용하면 코드를 더 단순하고 명확하게 만들 수 있습니다.
ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinnerCountry.getAdapter();
int position = adapter.getPosition(obj.getCountry());
spinnerCountry.setSelection(position);
도움이 됐으면 좋겠다.
이것이 나의 해결책이다.
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()));
및 getItem아래의 IndexById
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));
}
이것은 인덱스를 문자열별로 가져오는 간단한 방법입니다.
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;
}
.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);
int initialCursorPos = cursor.getPosition(); // Remember for later
int index = -1; // Not found
for (int i = 0; i < spinner.getCount(); i++) {
cursor.moveToPosition(i);
String itemText = cursor.getString(cursor.getColumnIndex(columnName));
if (itemText.equals(searchString)) {
index = i; // Found!
break;
}
}
cursor.moveToPosition(initialCursorPos); // Leave cursor as we found it.
return index;
}
}
또한 (Akhil의 답변을 개량한) 배열에서 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
}
};
리소스의 문자열 배열에서 스피너를 채워야 하고 서버에서 값을 선택한 상태로 유지해야 한다고 가정합니다.이것은 스피너에서 서버에서 선택한 값을 설정하는 한 가지 방법입니다.
pincodeSpinner.setSelection(resources.getStringArray(R.array.pincodes).indexOf(javaObject.pincode))
도움이 됐으면 좋겠네요! 추신, 코틀린에 암호가 있어요!
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개의 Spinner를 데이터베이스에서 동적으로 설정하고 싶었고 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<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
}
여기서 모든 기본 요소에 대해 만들 수 있는 캐스트 메서드는 문자열 및 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;
}
응용 프로그램이 마지막으로 선택한 스피너 값을 기억하도록 하려면 다음 코드를 사용합니다.
아래 코드는 스피너 값을 읽고 그에 따라 스피너 위치를 설정합니다.
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; }또한 최신 스피너 값이 존재하는 것을 알고 있는 코드 또는 필요에 따라 다른 코드를 입력합니다.이 코드 조각은 기본적으로 Shared Preferences에 spinner 값을 씁니다.
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();
cursor Loader를 사용하여 입력된 스피너에서 올바른 아이템을 선택하려고 할 때도 같은 문제가 있었습니다.먼저 표 1에서 선택하고 싶은 아이템의 ID를 취득한 후 Cursor Loader를 사용하여 스피너를 채웠습니다.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
}
앞의 답변 중 몇 가지는 매우 옳기 때문에, 저는 여러분 중 이러한 문제에 빠지지 않도록 하고 싶습니다.
을 「」로 .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_itemAndroid로 배송됩니다.
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값의 문자열 리소스 파일입니다.
values에 .xml 파일을 생성하기만 하면 됩니다.> > > >
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;
}
보다시피 어레이.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();
}
커스텀 어댑터를 REPECT[위치]와 같은 위치로 통과시켜야 합니다.정상적으로 동작합니다.
언급URL : https://stackoverflow.com/questions/2390102/how-to-set-selected-item-of-spinner-by-value-not-by-position
'programing' 카테고리의 다른 글
| C의 main() 함수에 유효한 시그니처는 무엇입니까? (0) | 2022.08.13 |
|---|---|
| Swing과 AWT의 차이점은 무엇입니까? (0) | 2022.08.13 |
| Vuex에서 업로드된 데이터를 어떻게 대기합니까? (0) | 2022.08.12 |
| 컬렉션을 반환해야 합니까, 아니면 스트림을 반환해야 합니까? (0) | 2022.08.12 |
| Ubuntu에서 libcrypto를 찾을 수 없습니다. (0) | 2022.08.12 |