Creating ArrayAdapter using xml resource and retrieving "id" or "value" fields using spinner
10,272
String[] SortByField= activity.getResources().getStringArray(
R.array.country_codes);
or
Arrayadapter adapterFillClass = ArrayAdapter.createFromResource(activity,
R.array.country_codes,
android.R.layout.simple_spinner_dropdown_item);
spinner.setadapter(adapterFillClass);
i hope it useful to you.
Author by
geekoraul
Updated on June 09, 2022Comments
-
geekoraul almost 2 years
I am trying to create a spinner, the values of which I am populating from a resource xml, using ArrayAdapter.
I also want to give the resource items some "id" or "value". How can i retrieve these values inside the onItemSelected() callback ?
Here is the Java code.
package com.waus.waus; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; public class Register extends Activity implements OnItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register); Spinner countrySpinner = (Spinner) findViewById(R.id.country_code_spinner); ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(this, R.array.country_codes, android.R.layout.simple_spinner_item); countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); countrySpinner.setOnItemSelectedListener(this); countrySpinner.setAdapter(countryAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long arg3) { // TODO Auto-generated method stub Toast.makeText(this, "THIS IS WHERE I WANT TO SHOW THE ID/VALUE" ,Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }
This is the XML file I want to use.
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="country_codes"> <item value="91">India</item> <item value="1">United States</item> // OR <item id="1">United States</item> </string-array> </resources>
How can it be done without using 2 resource files. i.e. one for codes and another for names.