基于枚举

时间:2017-11-11 12:58:44

标签: android enums

我正在开发一个带有枚举的应用程序来填充微调器和与它们相关的图片。当我尝试将spinner文本引用到strings.xml以获得使用手机语言设置的文本填充的微调器时,我只获取数字而不是文本。 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;
     } }

1 个答案:

答案 0 :(得分: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,因为您将从字符串中获取String值!

相关问题