Set values

I want to set the values ​​of android counter elements at runtime.

Here is what I still have:

final ArrayAdapter<String> calsListAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, calendarNames); eventCalendarList.setAdapter(calsListAdapter); eventCalendarList.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { calendarChoosen = availableCals.get(arg2); } public void onNothingSelected(AdapterView<?> arg0) { Logger.d("Cal Choosen", "fffffffffffffff"); } }); private List<AvailableCalendar> availableCals = new ArrayList<AvailableCalendar>(); private AvailableCalendar calendarChoosen; 

But the values ​​are not set. How can I do that?

+6
source share
2 answers

I'm going to assume that you are creating a Spinner adapter based on List<CharSequence> or something similar. You can use this to search for a selection, for example:

 String name = model.getName(); int index = list.indexOf(name); if (index != -1) spinner.setSelection(index); 

Obviously, if your model does not contain any "named" data, then there is nothing that could be selected in Spinner, so you may need to add some logic to process it. If the model has a "name", then find its index in the source list, which was used as the data source for the adapter. Only if the event found has been set, set the selector to the same index.

+10
source

I set spinner values ​​just like this:

 public class MainActivity extends Activity { private SharedPreferences prefs; private String prefName = "spinner_value"; int id=0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final List<String> list=new ArrayList<String>(); list.add("Item 1"); list.add("Item 2"); list.add("Item 3"); final Spinner sp=(Spinner) findViewById(R.id.spinner1); ArrayAdapter<String> adp= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list); adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sp.setAdapter(adp); prefs = getSharedPreferences(prefName, MODE_PRIVATE); id=prefs.getInt("last_val",0); sp.setSelection(id); sp.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1,int pos, long arg3) { prefs = getSharedPreferences(prefName, MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); //---save the values in the EditText view to preferences--- editor.putInt("last_val", pos); editor.commit(); Toast.makeText(getBaseContext(), sp.getSelectedItem().toString(), Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); } 
+2
source

Source: https://habr.com/ru/post/921334/


All Articles