当我创建模型类的对象时。我得到这个错误。我不知道如何将本地图像从可绘制对象传递到模型类。
这是我的模型课。
ggplot
这是我的适配器类代码。我正在将模型类传递给适配器。
public class Drawer {
private String image;
private String title;
public Drawer(String image, String title) {
this.image = image;
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
}
这就是我创建模型类对象的方式。
public class DrawerAdapter extends RecyclerView.Adapter<DrawerAdapter.ViewHolder> {
private List<Drawer> drawerList;
ItemNavigationDrawerBinding binding;
public DrawerAdapter(List<Drawer> drawerList) {
this.drawerList = drawerList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_navigation_drawer, parent, false);
return new ViewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Glide.with(holder.itemView.getContext()).load(drawerList.get(position).getImage()).into(holder.binding.imgMain);
holder.binding.tvMain.setText(drawerList.get(position).getTitle());
}
@Override
public int getItemCount() {
return drawerList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ItemNavigationDrawerBinding binding;
private ViewHolder(@NonNull ItemNavigationDrawerBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
答案 0 :(得分:0)
首先,要将Drawable保存到类中,我们必须使用整数值存储Drawable id,然后在适配器上,将drawable设置为imageview而不是drawable id。
class Drawer {
private int image;
private String title;
public Drawer(int image, String title) {
this.image = image;
this.title = title;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
在适配器上更换 Glide.with(holder.itemView.getContext())。load(drawerList.get(position).getImage())。into(holder.binding.imgMain);
与
Glide.with(holder.itemView.getContext()).load(holder.itemView.getContext().getDrawable(drawerList.get(position).getImage())).into(holder.binding.imgMain);
最后添加这样的项目
ArrayList<Drawer> drawerList = new ArrayList<>();
drawerList.add(new Drawer(R.drawable.your_drawable,"your title"));