To do this you need to have a custom spinner adapter and a custom class to hold these two variables.
Create a class which holds the name and country code for each of the items you will show.
Something like this:
public class Country {
public name;
public code;
}
Use an adapter of your choice for the Spinner. I would recommend BaseAdapter .
Override the getView and getDropdownView on the Adapter. All adapters have these methods.
The getView method will determine what is shown after the spinner is closed, so here you'll set the text of your TextView to the country code of the selected item.
On the getDropDownView you'll set the text of each of the options based on their positions to the name of the country you'll be showing.
Below you can find a minimal Adapter that will do what I have described above.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.ArrayList;
import java.util.List;
public class CountryAdapter extends BaseAdapter {
private List<Country> countryList;
public CountryAdapter() {
//Initialize the list however you need to.
countryList = new ArrayList<>();
}
@Override
public int getCount() {
return countryList.size();
}
@Override
public Object getItem(int position) {
return countryList.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
Context context = parent.getContext();
if (view == null || !view.getTag().toString().equals("NON_DROPDOWN")) {
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.spinner_item, parent, false);
view.setTag("NON_DROPDOWN");
}
String countryCode = countryList.get(position).code;
//Here you can set the label to the country code.
return view;
}
@Override
public View getDropDownView(int position, View view, ViewGroup parent) {
Context context = parent.getContext();
if (view == null || !view.getTag().toString().equals("DROPDOWN")) {
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.spinner_item_dropdown,
parent, false);
view.setTag("DROPDOWN");
}
String countryName = countryList.get(position).name;
//Here you set the text of your label to the name of the country.
return view;
}
private class Country {
public String name;
public String code;
}
}