【问题标题】:Create views programmatically in a RecyclerView.ViewHolder and passing arguments to it在 RecyclerView.ViewHolder 中以编程方式创建视图并将参数传递给它
【发布时间】:2016-06-06 16:36:51
【问题描述】:

我能否以编程方式在ViewHolder 中创建视图,而不是像所有示例中那样以经典方式从 XML 绑定它们? 另外,我的视图需要一个图像文件路径才能创建,如何将其传递给ViewHolder

protected static class ImagePreviewViewHolder extends RecyclerView.ViewHolder {
    public ImageView imageView;
    public LinearLayout page;

    public ImagePreviewViewHolder(View itemView) {
        super(itemView);
        page = createPage(filePath); // How do I pass the filepath?
    }
}

【问题讨论】:

    标签: android android-recyclerview


    【解决方案1】:

    你有没有尝试创建 查看项目查看 通过代码?

    例如:

    ll = new LinearLayout(this);
    ll.setOrientation(android.widget.LinearLayout.VERTICAL);
    ll.setLayoutParams(new ViewGroup.LayoutParams(-1,-1));
    ll.setBackgroundColor(0x88ff0000);
    
    tv = new TextView(this);
    tv.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
    tv.setText("sample text goes here");
    tv.setBackgroundColor(0x5500ff00);
    ll.addView(tv);
    

    ImagePreviewViewHolder holder = new ImagePreviewViewHolder(ll);
    

    【讨论】:

    • 所以我将项目传递给ViewHolder的构造函数?
    • 是的,您可以编写另一个以page为参数的构造函数。关于Views的创建,我觉得还是用onBindViewHolder方法比较好
    猜你喜欢
    • 2012-03-04
    • 2012-08-01
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多