Android 使用gilde应用程序中存储的可绘制图像
我从API接收图像链接,如: “” 但我想直接使用应用程序中的图像,因为许多用户在加载图像时遇到问题 因此,我将图像添加到应用程序中,并更改API以仅获取图像名称“image_1.png” 旧代码是:Android 使用gilde应用程序中存储的可绘制图像,android,drawable,Android,Drawable,我从API接收图像链接,如: “” 但我想直接使用应用程序中的图像,因为许多用户在加载图像时遇到问题 因此,我将图像添加到应用程序中,并更改API以仅获取图像名称“image_1.png” 旧代码是: View txtOption; if (AppConstant.arQuestionList.get(questionid).getArAnswer().get(i).getAtype() .equalsIg
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);
}
新代码(不工作):
只需使用:
int idDrawable = getResources().getIdentifier(imgName, "drawable", getPackageName());
Drawable drawable = ContextCompat.getDrawable(context, idDrawable);
Glide.with(context)
.load("")
.placeholder(drawable)
.into(imageView);
最后我发现了错误所在
// 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);
对不起,如果这个问题有点愚蠢的话。getDrawable无法使用上下文和imgName,因为无法读取字符串。另外.into(txtOption)表示“无法将方法解析”为(androi.view.view)。我认为我做的一切都是错的。当然,你不能在文本视图中添加图像,但可以在图像视图中添加。我编辑了我的答案。我尝试了新的方法,但仍然不起作用,请检查我在主要问题中做了什么。
// 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);