【问题标题】:Dynamic loading of images R.Drawable using variable使用变量动态加载图像 R.Drawable
【发布时间】:2011-10-30 21:43:11
【问题描述】:

我想我越来越近了,但仍然遇到资源错误。我在所有 3 个可绘制文件夹中都有一个名为 rock.png 的图像文件。

在我的布局 MAIN.XML 中:

 <ImageView android:id="@+id/rockId" android:src="@drawable/rock"></ImageView>

在我的代码中:

            int resID = getResources().getIdentifier("rockId" , "id", "com.testing");
            ImageView image = (ImageView) findViewById(resID);

我仍然在我的错误目录中看到这个:

10-30 17:36:24.485: WARN/ResourceType(74): Resources don't contain package for resource number 0x7f020000

对我可能做错了什么有什么想法吗?欢迎任何提示

【问题讨论】:

    标签: android


    【解决方案1】:

    找到控件:

    ImageView image = (ImageView) findViewById(R.id.rockId);
    

    要从drawable动态加载图像,我使用这个函数

        public static int getDrawable(Context context, String name)
        {
            Assert.assertNotNull(context);
            Assert.assertNotNull(name);
    
            return context.getResources().getIdentifier(name,
                    "drawable", context.getPackageName());
        }
    

    这将返回您的可绘制对象的 id,现在您只需在控件中设置图像:

    image.setImageResource(int Id);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 2017-03-11
      相关资源
      最近更新 更多