正如标题中所提到的,我在RecyclerView
里面需要填充20
张图片。由于图片在drawable
中可用,因此我尝试以adapter
的{{1}}编程方式设置这些图片。
RecyclerView
现在,这显然不适用于Android工作室说:
错误的第二个参数类型。找到:'java.lang.String',必需:'int'
为此,已存在一个解决方案:Setting Android images from string value
然而,当我尝试时:
@Override
public void onBindViewHolder(HomeTeamViewHolder homeTeamViewHolder, int i)
{
homeTeamViewHolder.teamName.setText(d1.teams.get(i));
String str = "R.drawable.e0";
homeTeamViewHolder.home_teams.setImageDrawable(ContextCompat.getDrawable(homeTeamViewHolder.mcontext,str));
}
在 int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");
内:
onBindViewHolder()
Android Studio说:
无法从静态上下文引用非静态方法
@Override public void onBindViewHolder(HomeTeamViewHolder homeTeamViewHolder, int i) { homeTeamViewHolder.teamName.setText(d1.teams.get(i)); //String str = "R.drawable.e0"; int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name"); homeTeamViewHolder.home_teams.setImageDrawable(ContextCompat.getDrawable(homeTeamViewHolder.mcontext,resourceId)); }
所以,问题是:如何解决这个问题?
答案 0 :(得分:1)
您可以在构造函数中将上下文传递给Adapter。然后,您可以通过该上下文访问getResources()。
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
...
private Context context;
public MyAdapter(Context context, Other_arguments_you_need) {
this.context = context;
// set other arguments
}
...
@Override
public void onBindViewHolder(HomeTeamViewHolder homeTeamViewHolder, int i)
{
homeTeamViewHolder.teamName.setText(d1.teams.get(i));
int resourceId = context.getResources().getIdentifier("testimage", "drawable", "your.package.name");
homeTeamViewHolder.home_teams.setImageDrawable(ContextCompat.getDrawable(homeTeamViewHolder.mcontext,resourceId));
}
}
答案 1 :(得分:0)
通过将上下文传递给适配器来修复它。
Context mcontext = itemView.getContext();
然后,在onBindViewHolder()
内:
@Override
public void onBindViewHolder(HomeTeamViewHolder homeTeamViewHolder, int i)
{
homeTeamViewHolder.teamName.setText(d1.teams.get(i));
String x = "e"+i;
int resourceId = homeTeamViewHolder.mcontext.getResources().getIdentifier(x, "drawable", "com.udacity.yaafl");
homeTeamViewHolder.home_teams.setImageDrawable(ContextCompat.getDrawable(homeTeamViewHolder.mcontext,resourceId));
}
答案 2 :(得分:0)
通过此
获取资源的整数ID int resourceId = homeTeamViewHolder.itemView.getResources().getIdentifier("testimage", "drawable", "your.package.name");