如何根据动态可绘制名称从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)'
试试这个你忘了绑定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);
}
似乎你忘记了bind
ImageView
。
imageView = (ImageView) findViewById(R.id.image_view_id);
试试这个:
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());
}