2017-11-11 80 views
1

我正在開發一個應用程序,使用枚舉來填充微調器以及與它們關聯的圖片。當我嘗試將spinner文本引用到strings.xml以使用手機中設置的語言填充spinner時,我只能獲取數字而不是文本。 getNombres()用於填充主活動中的微調器。基於枚舉在微調器上更改語言文本

下面是代碼:

public enum TipoLugar { 
    OTROS(R.string.otros, R.drawable.otros), 
    RESTAURANTE(R.string.restaurante ,R.drawable.restaurante), 
    BAR(R.string.restaurante , R.drawable.bar), 
    COPAS(R.string.copas , R.drawable.copas), 
    ESPECTACULO(R.string.restaurante , R.drawable.espectaculos), 
    HOTEL(R.string.hotel , R.drawable.hotel), 
    COMPRAS(R.string.compras , R.drawable.compras), 
    EDUCACION(R.string.educacion ,R.drawable.educacion), 
    DEPORTE(R.string.deporte , R.drawable.deporte), 
    NATURALEZA(R.string.naturaleza , R.drawable.naturaleza), 
    GASOLINERA(R.string.gasolinera , R.drawable.gasolinera), 
    VIVIENDA(R.string.vivienda , R.drawable.vivienda), 
    MONUMENTO(R.string.monumento ,R.drawable.monumento); 
    private final int texto; 
    private final int recurso; 

    TipoLugar(int texto,int recurso) { 

     this.texto = texto; 
     this.recurso = recurso; 
     } 

    public String getTexto() { 
     return String.valueOf(texto); 
    } 

    public int getRecurso() { 
     return recurso; 
    } 

    public static String[] getNombres() { 
     String[] resultado = new String[TipoLugar.values().length]; 
     for (TipoLugar tipo : TipoLugar.values()) { 
      resultado[tipo.ordinal()] = String.valueOf(tipo.texto); 
     } 
     return resultado; 
    } } 

回答

0

兩種方式:

首先從你的方法刪除靜態關鍵字,如果它是在MainActivity,改變你的方法爲:

public String[] getNombres() { 
    String[] resultado = new String[TipoLugar.values().length]; 
    for (TipoLugar tipo : TipoLugar.values()) { 
     resultado[tipo.ordinal()] = getString((tipo.texto)); 
    } 
    return resultado; 
} 

第二種方法是保留靜態字,但是現在您每次要調用方法時都必須通過Context

public static String[] getNombres(Context context) { 
    String[] resultado = new String[TipoLugar.values().length]; 
    for (TipoLugar tipo : TipoLugar.values()) { 
     resultado[tipo.ordinal()] = context.getString((tipo.texto)); 
    } 
    return resultado; 
} 

而且你會在你的MainActivity打電話給你的方法是這樣的:

getNombres(this); 

從這裏,你會得到String!而非int因爲你會從琴絃字符串值!

+0

非常感謝。我做了你的第二個建議,並完美地工作 – spcarman

+0

好的@spcarman歡迎您。但是還有一件事是接受我的答案,因爲它解決了你的問題(stackoverflow風格)。點擊答案左側的勾號。你是唯一一個能夠這樣做的人,因爲你問了這個問題! **快樂編碼!**。 – Xenolion