我正在Android Studio上开发一个翻译应用程序。我已经使用Map创建了我的语言键和值,我想将用户选择的键的值传递到URL。例如,如果用户从Spinner中选择法语,则应将"fr"传递到url进行翻译。我怎样才能做到这一点?下面是我的Java活动代码。我正在使用最新的安卓工作室。
spinner = (Spinner) findViewById(R.id.spinner);
final Map<String, String> flanguages = new HashMap<String, String>();
flanguages.put("Arabic", "ar");
flanguages.put("English", "en");
flanguages.put("French", "fr");
flanguages.put("Hausa", "ha");
flanguages.put("Igbo", "ig");
flanguages.put("Yoruba", "yo");
flanguages.put("Japanese", "ja");
final List<String> list = new ArrayList<String>(flanguages.keySet());
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
spinner.setPrompt("Select Language To Translate");
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinner.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
在您的onItemSelected回调中
String key = list.get(position);
String countryCode = flanguages.get(key);
countryCode是您需要的
spinner.getItemAtPosition(position).toString(); //returns country Full-name
此行提供所选项目,即国家名称,但不是其缩写。要获取缩写,请使用HashMap(使用Key获取Value(。例如:这里的关键字是"法国",它的值是"fr">
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String key = spinner.getItemAtPosition(position).toString(); //ex: this gives France
// String key = list.get(position); // or use can use this,//ex: this also gives France
String countryCode = flanguages.get(key); //ex: this gives "fr"
//api integration
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});