要使用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
文件中添加翻譯。