Creating an ArrayAdapter using an xml resource and getting the id or value fields using a spinner

I am trying to create a spinner whose values ​​I am populating from an xml resource using an ArrayAdapter.

I also want to give the resource elements some "id" or "value". How can I get 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 to do this without using 2 resource files. that is, for codes, and the other for names.

+4
source share
1 answer
 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 you find this useful.

+8
source

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


All Articles