在RecyclerView.ViewHolder中以编程方式创建视图并将参数传递给它

时间:2016-06-06 08:02:26

标签: android android-recyclerview

我是否可以在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?
    }
}

1 个答案:

答案 0 :(得分:3)

你试过创造吗?    查看itemView 通过代码?

代表:

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);