如何在 Spinner 中获取值并将值传递给 url 以进行翻译

How to get Value in Spinner and pass the Value to url for translate

我正在 Android Studio 上开发 翻译应用程序 。我已经使用 Map 创建了我的语言键和值,我想将用户选择的键的值传递给 URL。例如,如果用户从微调器中选择法语,则 "fr" 应该传递给 url 进行翻译。我怎样才能做到这一点?下面是我的 Java Activity 代码。我正在使用最新的 Android Studio。

     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);

国家代码就是你所需要的

spinner.getItemAtPosition(position).toString(); //returns country Full-name

这一行给出了您选择的项目,即国家名称,但不是其缩写。获取缩写使用HashMap(使用Key获取Value)。例如:这里的key是"France",它的值是"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) {

    }
});