有的时候想在RecyclerView中显示这一组图片,每一个都R.drawable.xxxx会很麻烦
public static int getDrawableId(String var) {
try {
Field field = R.drawable.class.getField(var);
return field.getInt(new R.drawable());
} catch (Exception e) {
return 0;
}
}
@Override
public void onBindViewHolder(@NonNull HeadAdapter.HeadViewHolder holder, int position) {
//资源文件名字
String resName = "head" + position;
//获取headX对应的id
int drawableId = FunctionUtils.getDrawableId(resName);
Glide.with(context).load(drawableId).into(holder.ivHead);
}
AndroidStudio 3.6 上面的方法好像用不了了,会报错,下面的可以
public static int getDrawableId(Context context, String var) {
try {
int imageId = context.getResources().getIdentifier(var, "drawable", context.getPackageName());
return imageId;
} catch (Exception e) {
return 0;
}
}