我试图在卡片视图上显示图像和标题。代码应该从文本文件中获取图像名,并将其转换为图像的in,这些图像已经在可绘制文件中。但是当我在模拟器上运行我的代码时,只显示标题。所以我使用Log.d来检查值,结果显示图像的名称已经存在,但是资源ID是0。我一直在寻找同样的问题和解决方案,但都没有效果。还是有更好的方法来检索适配器中的图像in?
@Override
public void onBindViewHolder(@NonNull MyRecyclerViewAdapter.MyViewHolder myViewHolder, int i) {
News news = news_list.get(i);
myViewHolder.textView_title.setText(news.getNews_title());
mContext = mContext.getApplicationContext();
String imageName = news.getImage_name();
int resID = mContext.getResources().getIdentifier(imageName, "drawable", mContext.getPackageName());
Log.d("here",news.getImage_name());
Log.d("here", String.valueOf(resID));
final String URL = news.getURLs();
myViewHolder.imageView_image.setImageResource(resID);
以上是在我的回收适配器的onBindViewHolder代码,以显示标题和图像中的硬视图。
2019-11-10 13:09:00.688 29179-29179/com.example.assignment4_task1 D/here: cyber5.png
2019-11-10 13:09:00.689 29179-29179/com.example.assignment4_task1 D/here: 0
2019-11-10 13:09:00.707 29179-29179/com.example.assignment4_task1 D/here: cyber1.png
2019-11-10 13:09:00.707 29179-29179/com.example.assignment4_task1 D/here: 0
2019-11-10 13:09:00.782 29179-29179/com.example.assignment4_task1 D/here: ai1.png
2019-11-10 13:09:00.782 29179-29179/com.example.assignment4_task1 D/here: 0
2019-11-10 13:09:00.799 29179-29179/com.example.assignment4_task1 D/here: ai3.png
2019-11-10 13:09:00.799 29179-29179/com.example.assignment4_task1 D/here: 0
2019-11-10 13:09:00.824 29179-29179/com.example.assignment4_task1 D/here: cyber5.png
2019-11-10 13:09:00.824 29179-29179/com.example.assignment4_task1 D/here: 0
2019-11-10 13:09:00.842 29179-29179/com.example.assignment4_task1 D/here: ai2.png
2019-11-10 13:09:00.842 29179-29179/com.example.assignment4_task1 D/here: 0
2019-11-10 13:09:00.860 29179-29179/com.example.assignment4_task1 D/here: ai4.png
2019-11-10 13:09:00.861 29179-29179/com.example.assignment4_task1 D/here: 0
以上是Logcat的结果。图像名称已经存在,我并没有故意将+".png“放在名称后面,但是资源ID仍然返回0。
发布于 2019-11-10 07:02:36
从资源名称中删除.png。getIdentifier工作时没有文件扩展名。
String imageName = news.getImage_name().substring(0, str.lastIndexOf('.'))
如果您想使用您的文件扩展名,请使用“资产”文件夹(我认为在您的情况下使用“资产”文件夹更好):
Drawable d = Drawable.createFromStream(getAssets().open("Images/image_name.png"), null);
https://stackoverflow.com/questions/58786038
复制相似问题