我收到来自API的图片链接,例如: “http://host/skin/images/answer_picture/image_1.png”
但是我想直接从应用程序中使用这些图像,因为许多用户在加载图像时遇到了问题。
所以我将图片添加到应用程序中,然后更改API以仅获取图像名称“image_1.png”。
旧代码是:
View txtOption;
if (AppConstant.arQuestionList.get(questionid).getArAnswer().get(i).getAtype()
.equalsIgnoreCase("image")) {
txtOption = new ImageView(this);
try {
Glide.with(QuestionActivity.this).load(AppConstant.arQuestionList.get(questionid)
.getArAnswer().get(i).getAnswer()).override(60, 60).into((ImageView)
txtOption);
}catch (OutOfMemoryError e){
e.printStackTrace();
}
txtOption.setPadding(5, 5, 5, 5);
} else {
txtOption = new TextView(this);
((TextView) txtOption).setText(AppConstant.arQuestionList.get(questionid)
.getArAnswer().get
(i).getAnswer());
((TextView) txtOption).setTextColor(getResources().getColor(R.color.answer_color));
((TextView) txtOption).setTypeface(tf, Typeface.BOLD);
((TextView) txtOption).setGravity(Gravity.CENTER);
txtOption.setPadding(10, 20, 10, 20);
}
新代码(不工作):
// get the img name example: Skill_test.png
String imgName = AppConstant.arQuestionList.get(questionid)
.getArAnswer().get(i).getAnswer();
// delete image name extension
if (imgName.endsWith(".png")) {
imgName = imgName.substring(0, imgName.length() - 5);
}
String uri = "drawable/"+imgName;
int idDrawable = getResources().getIdentifier(uri,"drawable", getPackageName());
Drawable drawable = ContextCompat.getDrawable(QuestionActivity.this, idDrawable);
Glide.with(QuestionActivity.this)
.load("")
.placeholder(drawable)
.into((ImageView)txtOption);
答案 0 :(得分:0)
只需使用:
int idDrawable = getResources().getIdentifier(imgName, "drawable", getPackageName());
Drawable drawable = ContextCompat.getDrawable(context, idDrawable);
Glide.with(context)
.load("")
.placeholder(drawable)
.into(imageView);
答案 1 :(得分:0)
最后我弄清楚错误是什么
// get the img name, example: Skill_Hero_Skill-Name.png
String imgName = AppConstant.arQuestionList.get(questionid)
.getArAnswer().get(i).getAnswer();
// delete image name extension
if (imgName.endsWith(".png")) {
imgName = imgName.substring(0, imgName.length() - 4);
}
// string to lowercase
imgName = imgName.toLowerCase();
// replace "-" for "_"
imgName = imgName.replace('-','_');
String uri = "drawable/"+imgName.toLowerCase();
int imageResource = getResources().getIdentifier(uri,"drawable", getPackageName());
Glide.with(QuestionActivity.this)
.load(imageResource)
.crossFade()
.override(60, 60)
.into((ImageView)txtOption);