【问题标题】:Create ImageView depending on a varaible in Android根据Android中的变量创建图像视图
【发布时间】:2016-06-29 06:02:31
【问题描述】:

我有一个 ImageView,它根据一个人的国籍显示一个国家的国旗。 目前,我使用这样的 Switch-Case 语句来做到这一点:

public in getFlag() {
        switch (nationality) {
        case "GER":
            return R.drawable.ger;
        case "AUS":
            return R.drawable.aus;
        case "FRA":
            return R.drawable.fra;
    }
}

但是国家多于 3 个。所以我必须为每个国籍添加一个案例陈述。 有没有更好的机会……更像:

imgFlag.setImageResource(R.drawable.(participants.getNationality());

【问题讨论】:

    标签: android dynamic imageview


    【解决方案1】:

    有反射

    try {
      Field field = R.drawable.class.getField(participants.getNationality().toLowerCase());
    } catch (NoSuchFieldException e) {
      e.printStackTrace();
    }
    
    try {
      if(field != null)
        imgFlag.setImageResource(field.getInt(null));
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
    

    【讨论】:

      【解决方案2】:

      以下方法根据字符串返回一个资源id:

      public static int getResId(String resName, Class<?> c) {
      
          try {
              Field idField = c.getDeclaredField(resName);
              return idField.getInt(idField);
          } catch (Exception e) {
              e.printStackTrace();
              return -1;
          } 
      }
      

      你现在应该有:

      int resourceId = getResId(nationality.toLowerCase(), YourCurrentActivity.this.getClass());
      imgFlag.setImageResource(resourceId);
      

      【讨论】:

      • 谢谢,但是 getResId 方法需要一个字符串和类>。但是当我 getResId(nationality.toLowerCase());我只传递一个字符串。
      • 我的错,我忘了第二个参数,试试这个: int resourceId = getResId(nationality.toLowerCase()), YourCurrentActivity.this.getClass());
      • 对不起,我是初学者 .. 现在我得到一个致命异常 Android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
      • 首先确保您的drawable存在于您的资源文件夹中,然后您应该检查您放入参数的字符串是否不为空,是否拼写正确,是否与现有资源匹配等。因为实际上您是在 getResId 方法中出现错误,并且“catch”块返回“-1”作为 ID,我猜它不存在。
      • 我检查了所有国籍字符串和资源名称。但是还是有这个错误信息。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2011-06-18
      • 2011-03-06
      • 2021-11-25
      • 1970-01-01
      相关资源
      最近更新 更多