2017-03-01 88 views
0

我有一個enum類爲兩種類型的數學值,它們是,AMOUNTPERCENTAGE如何爲ENUM設置文本並支持多種語言?

這兩個是單選按鈕,取決於用戶選擇的單選按鈕。文本被相應地設置。

直到現在,我的應用程序只有一種語言,但現在我已經使它成爲多語言。如何根據語言設置ENUM的文字?

這是我enum

public enum DiscountTypeEnum { 
    AMOUNT, 
    PERCENTAGE; 
    private DiscountTypeEnum() { 
    } 
} 

我想基於什麼discountType用戶選擇要設置的字符串,

for (DiscountTypeEnum discountType : DiscountTypeEnum.values()) { 
    RadioButton discountTypeButton = new RadioButton(getContext()); 
    // below is where I need to set the text from string resource file 
    // setText(R.string.AMOUNT) or setText(R.string.PERCENTAGE) 
    discountTypeButton.setText(discountType.name()); 
    discountTypes.addView(discountTypeButton); 
} 

回答

0

而不是直接使用枚舉的名稱,你可以使用具有區域限定符的字符串資源。你可以存儲在每個區域設置單獨strings.xml文件不同語言的字符串,然後用

getResources().getString(R.string.my_string); 

在運行時,它會給你的資源爲設備的當前語言,如果它是可用的閱讀資源。

官方文檔中更多信息:https://developer.android.com/training/basics/supporting-devices/languages.html

0
enum FRUITS { 
    APPLE(R.string.apple), 
    BANANA(R.string.banana); 

    private @StringRes 
    int label; 

    FRUITS(@StringRes int label) { this.label = label; } 

    @Override 
    public String toString() { 
     return MyApplication.getApplicationContext().getString(label); 
    } 
} 

對於非機器人:https://softwareengineering.stackexchange.com/questions/256806/best-approach-for-multilingual-java-enum

+0

我ENUM是一個Java類,而不是機器人。在那種情況下,我怎樣才能使用多語言字符串? – baabidi

+0

檢查我編輯的答案 –