2017-11-11 81 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