You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Model中的文本传递给Adapter?Android开发求助

解决Category Model数据无法传递到GalleryAdapter的问题

常见排查与修复步骤

1. 检查Category Model的Getter方法

确保Model类为category_name字段提供了正确的Getter方法,规范示例:

public class Category {
    private int cid;
    private String categoryName; // 建议用驼峰命名更符合Java规范

    public Category(int cid, String categoryName) {
        this.cid = cid;
        this.categoryName = categoryName;
    }

    // 对应字段的Getter方法
    public String getCategoryName() {
        return categoryName;
    }

    public int getCid() {
        return cid;
    }
}

若你坚持用category_name作为字段名,Getter方法需为getCategory_name(),注意名称必须严格对应,否则无法正确获取字段值。

2. 确认GalleryAdapter的数据绑定逻辑

在onBindViewHolder方法中,必须正确调用Model的Getter获取文本,并绑定到布局控件,示例:

public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.ViewHolder> {
    private List<Category> mCategoryList;

    public GalleryAdapter(List<Category> categoryList) {
        mCategoryList = categoryList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.your_item_layout, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Category category = mCategoryList.get(position);
        // 调用Getter获取文本并设置到TextView
        holder.categoryTv.setText(category.getCategoryName());
    }

    @Override
    public int getItemCount() {
        return mCategoryList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView categoryTv;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            // 此处ID必须和布局文件中的TextView ID完全一致
            categoryTv = itemView.findViewById(R.id.tv_category);
        }
    }
}

3. 验证布局文件的控件ID

检查item布局文件中的TextView ID是否与Adapter中findViewById的ID完全匹配,示例:

<TextView
    android:id="@+id/tv_category"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/black"
    android:textSize="16sp"/>

ID的大小写、下划线都不能出错,否则控件会绑定失败,无法设置文本。

4. 确认数据传递到Adapter的正确性

在Activity/Fragment中设置Adapter时,确保已将填充好数据的List传递给Adapter,同时为RecyclerView设置LayoutManager:

// 初始化数据
List<Category> categoryList = new ArrayList<>();
categoryList.add(new Category(1, "自然风光"));
categoryList.add(new Category(2, "城市建筑"));

// 设置Adapter
GalleryAdapter adapter = new GalleryAdapter(categoryList);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

若以上步骤仍未解决问题,请补充你的Category Model完整代码、GalleryAdapter完整代码和item布局代码,以便进一步定位问题。

内容的提问来源于stack exchange,提问作者atozcodes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 12:20:02