要使用Spinner Adapter实现国际化支持,你需要遵循以下步骤:
- 创建一个包含语言名称和语言代码的字符串数组。例如,在
res/values/strings.xml
文件中添加以下内容:
- English (US)
- Español (ES)
- Français (FR)
- en_US
- es_ES
- fr_FR
- 在布局文件中添加一个Spinner控件。例如,在
res/layout/activity_main.xml
文件中添加以下内容:
- 在Activity或Fragment中设置Spinner Adapter。例如,在
MainActivity.java
文件中添加以下内容:
import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Spinner languageSpinner = findViewById(R.id.language_spinner); // Create an ArrayAdapter using the languages array and a default spinner layout ArrayAdapteradapter = ArrayAdapter.createFromResource(this, R.array.languages, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner languageSpinner.setAdapter(adapter); // Set an OnItemSelectedListener on the spinner languageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView> parent, View view, int position, long id) { // Get the selected language code String languageCode = getResources().getStringArray(R.array.language_codes)[position]; // Change the locale based on the selected language code Locale locale = new Locale(languageCode); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); // Restart the activity to apply the changes recreate(); } @Override public void onNothingSelected(AdapterView> parent) { // Do nothing } }); } }
现在,当用户从Spinner中选择一种语言时,应用程序将更新其语言设置并重新启动。请注意,为了使此示例正常工作,你需要为每种支持的语言提供相应的翻译。你可以在res/values-
目录下的strings.xml
文件中添加翻译。