【问题标题】:How to convert a URI to an integer drawable and add it to int[] array of drawables?如何将 URI 转换为整数可绘制对象并将其添加到可绘制对象的 int[] 数组中?
【发布时间】:2015-03-25 13:06:49
【问题描述】:

我有一个存储可绘制对象的整数数组:

 menuIcons = new int[] {R.drawable.icon_default,R.drawable.icn_delete_45x45,
    R.drawable.icn_delete_45x45,R.drawable.icn_delete_45x45 };

我使用这个数组来填充列表中的图像。现在的问题场景是,对于第一行,我的 draable 文件夹中没有图像,但我的数据库中有一个 URI,这个 URI 可以引用 SDCard 上的服务器 URL 或本地 URI,甚至是内容提供程序 URI。我有一个功能来处理显示来自各种来源的图像。

这里的问题是我不知道如何在我的可绘制的 int 数组的位置 0 处添加这个 URI,或者这甚至可能吗?

作为胶带解决方案,我可以将此 URI 传递给我的 ListAdapter 类的构造函数并检测位置 0 并相应地显示图像。但这不是一个适当的解决方案。

【问题讨论】:

    标签: android android-drawable


    【解决方案1】:

    作为资源 id 的数组,不可能做你想做的事。原因很简单:你引用的图片位于别处,不属于你应用的静态资源。

    更新:

    您可以从以下内容开始:

    Object[] menuIcons = { "some://uri", "some://other_uri", R.drawable.icon_default,R.drawable.icn_delete_45x45,
    R.drawable.icn_delete_45x45,R.drawable.icn_delete_45x45 };
    
    List<Drawable> drawables = new ArrayList<>();
    
    for( Object ic : menuIcons ){
      switch( ic.getClass().getSimpleName() ){
        case "int":
        case "Integer":
          drawables.add( getResources().getDrawable( (int)ic );
          break;
    
        case "String":
          drawables.add( getDrawableFromSomeUri( (String)ic ) );
          break;
    
        case "URL":
          drawables.add( getDrawableFromSomeURL( (URL)ic ) );
          break;
    
      }
    }
    

    您可以使用Map 而不是List 来简化查找

    【讨论】:

    • 不幸的是,我将不得不使用管道胶带解决方案
    • 任何标题?也许是一个链接?