我创建了一个回收视图,其中显示了我的数据库中所有已注册的宠物,并附有根据宠物种类而有所不同的图像。
现在我的问题是每当我在我的数据库中注册一只宠物时,每张注册的宠物都会显示相同的图像。
我所做的是在我的数据库中获取宠物的品种,并将其与我为区分不同品种的每个品种的字符串进行比较。
所以有人能以正确的方式展示如何做到这一点吗?
这是我的recyclerview的代码
public class db_adapter extends RecyclerView.Adapter<pet_viewholder>
{
Context data_context;
ArrayList<db_getItem> items;
public db_adapter( Context data_context, ArrayList<db_getItem> items) {
this.data_context=data_context;
this.items=items;
}
@Override
public pet_viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.reg_view_pet, parent, false);
return new pet_viewholder(view, data_context, items);
}
public void add(db_getItem pet) {
items.add(0, pet);
notifyItemInserted(0);
}
@Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
@Override
public void onBindViewHolder(pet_viewholder holder, int position) {
holder.pet_name.setText(items.get(position).getPet_name());
holder.pet_breed.setText(items.get(position).getPet_breed());
holder.pet_age.setText(items.get(position).getPet_age());
holder.pet_bday.setText(items.get(position).getPet_bday());
holder.position=position;
}
@Override
public int getItemCount() {
return items.size();
}
}
以下是我的Viewholder用于显示宠物图像的代码。
public class pet_viewholder extends RecyclerView.ViewHolder {
TextView pet_name;
TextView pet_breed;
TextView pet_age;
TextView pet_bday;
ImageView pet_image;
RecyclerView recyclerView;
ArrayList<db_getItem> arrayList;
db_adapter adapter;
Context data_context1;
pet_database pet_database;
Cursor c;
public pet_viewholder(final View itemView, final Context data_context1, ArrayList<db_getItem> arrayList) {
super(itemView);
this.data_context1=data_context1;
this.arrayList=arrayList;
pet_name=(TextView)itemView.findViewById(R.id.name_pet);
pet_breed=(TextView)itemView.findViewById(R.id.breed_pet);
pet_age=(TextView)itemView.findViewById(R.id.age_pet);
pet_bday=(TextView)itemView.findViewById(R.id.bday_pet);
pet_image=(ImageView) itemView.findViewById(R.id.pic_breed);
recyclerView=(RecyclerView)itemView.findViewById(R.id.reg_pet);
pet_database = new pet_database(data_context1);
c=pet_database.queryData("select * from pet_registered");
if (c.moveToFirst()) {
do {
String pos=c.getString(3);
String beagle="Beagle";
String bulldog="Bull Dog";
if(beagle.equals(pos)){
pet_image.setImageResource(R.drawable.beagle);
}
else if(bulldog.equals(pos)){
pet_image.setImageResource(R.drawable.bulldog);
}
} while (c.moveToNext());
}
}
}
答案 0 :(得分:0)
根据您的要求代码 onBindViewHolder
注意:onBindViewHolder将每次调用为每行设置数据。
String bread = items.get(position).getPet_breed();
if(bread.equals("breadOne")
{
holder.pet_image.setImageResource(R.drawable.beagle);
}
else if(bread.equals("breadTwo")
{
pet_image.setImageResource(R.drawable.bulldog);
}