如何根据动态可绘制名称从PNG设置图像

问题描述 投票:0回答:3

如何根据动态可绘制名称从PNG设置图像?

我使用以下代码来获取错误。

我有PNG:

R.drawable.model_1.png
R.drawable.model_2.png
... and etc

try
{
    String imageName = "model_" + uv.categoryID;
    int id = context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());
    imageView.setImageResource(id);
}
catch(Exception ex)
{
    Log.e(TAG, ex);
}

错误

尝试在空对象引用上调用虚方法'void android.widget.ImageView.setImageResource(int)'

java android
3个回答
1
投票

试试这个你忘了绑定imageView

try
 {
    ImageView imageView = (ImageView) findViewById(R.id.Yourimageview);
    String imageName = "model_" + uv.categoryID;
    int id = context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());
    imageView.setImageResource(id);
 }
 catch(Exception ex)
 {
     Log.e(TAG, ex);
 }

2
投票

似乎你忘记了bind ImageView

imageView = (ImageView) findViewById(R.id.image_view_id);

1
投票

试试这个:

    try
    {
        ImageView imageView = (ImageView)findViewById(R.id.imageView);
        int categoryID = 0;
        String imageName = "model_" + categoryID;
        int id = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());
        imageView.setImageResource(id);
    }
    catch(Exception ex)
    {
        Log.e("NIKHIL", ex.toString());
    }
© www.soinside.com 2019 - 2024. All rights reserved.