要使用Spinner Adapter实现国际化支持,你需要遵循以下步骤:
res/values/strings.xml
文件中添加以下内容: <item>English (US)</item>
<item>Español (ES)</item>
<item>Français (FR)</item>
<!-- Add more languages as needed -->
</string-array><string-array name="language_codes">
<item>en_US</item>
<item>es_ES</item>
<item>fr_FR</item>
<!-- Add more language codes as needed -->
</string-array>
res/layout/activity_main.xml
文件中添加以下内容:<Spinner
android:id="@+id/language_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
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
ArrayAdapter<CharSequence> adapter = 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-<language_code>
目录下的strings.xml
文件中添加翻译。