I want to create a spinner for selecting a country and getting its country code.
I already found this item list:
These are ISO 3166-1 alpha-2 codes. You can find a complete list on the ISO's website.
Running the following code in the JavaScript console (tested using Chrome) gives you a map from codes to countries in JSON format:
var result = {}
var rows = document.getElementsByTagName('tr');
for (var i=1; i<rows.length; i++) {
var code = rows[i].cells[0].textContent;
var country = rows[i].cells[1].textContent;
result[code] = country;
}
console.log(JSON.stringify(result));
I have a cleaner solution for you. You can use Country Code Picker (CCP) library directly.It will save you from boilerplate code. You just need to place the CountryCodePicker view in your layout XML. This is CCP view .
Your view will look like with your phone editText.
Download Sample application from PlayStore.
Clicking on CCP will open a dialog with a list of country to select from. Here you can search country with country name, code name, phone code. It also gives an option to autoformat phone number.
Selected country details can be read easily. For more details go to Library's Github page.
in gradle :
// country picker
implementation 'com.hbb20:ccp:1.7.1'
in XML
<com.hbb20.CountryCodePicker
android:id="@+id/ccp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@color/colorGreyF5"
android:onClick="onCountryPickerClick"
android:paddingStart="@dimen/margin_10" />
in Activity :
CountryCodePicker ccp;
ccp = findViewById(R.id.ccp);
public void onCountryPickerClick(View view) {
ccp.setOnCountryChangeListener(new CountryCodePicker.OnCountryChangeListener() {
@Override
public void onCountrySelected() {
//Alert.showMessage(RegistrationActivity.this, ccp.getSelectedCountryCodeWithPlus());
selected_country_code = ccp.getSelectedCountryCodeWithPlus();
}
});
}