【发布时间】:2014-12-21 23:45:48
【问题描述】:
我有一个关于 RecyclerView 的问题。我试图学习 RecyclerView 但我遇到了一个问题。我正在动态创建所有视图。所以,假设我有一个 ContentLinearLayout。我的问题从“refreshContent”方法开始。我多次调用这个。但是,即使在第一次调用时,RecyclerView 的内部视图仍保持其背景图像大小(我猜某处有一些隐含的 WRAP_CONTENT)。我找不到将按钮的高度和宽度与 RecyclerView 的高度相等的方法。我尝试迭代 RecyclerView 并为每个孩子设置布局参数,但没有奏效。此外,我尝试在“onBindViewHolder”中设置布局参数,但这也不起作用。
任何帮助将不胜感激。
public class ContentLinearLayout extends LinearLayout {
private RecyclerView rvCon;
private LinearLayout llCon;
public ContentLinearLayout(Context context) {
super(context);
this.init(context);
}
public ContentLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.init(context);
}
private void init(Context c){
this.setOrientation(LinearLayout.VERTICAL);
this.setBaselineAligned(false);
rvCon = new RecyclerView(c);
LinearLayout.LayoutParams recyclerPrms = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f);
recyclerPrms.setMargins(0, 0, 0, 0);
rvCon.setLayoutParams(recyclerPrms);
LinearLayoutManager manager = new LinearLayoutManager(c, LinearLayoutManager.HORIZONTAL, false);
rvCon.setLayoutManager(manager);
addView(rvCon);
rvCon.setPadding(0, 0, 0, 0);
LinearLayout llCon = new LinearLayout(c);
llCon.setOrientation(LinearLayout.HORIZONTAL);
llCon.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0, 3f));
llCon.setBaselineAligned(false);
addView(container);
...
}
private void refreshContent(Context ctx, Content content){
rvCon.setAdapter(new ContentAdapter(ctx, content));
}
}
public class ContentAdapter extends RecyclerView.Adapter<ImageButtonHolder>{
private Context mContext;
private Content mContent;
public ContentAdapter(Context c, Content content){
mContext = c;
mContent = content
}
@Override
public int getItemCount() {
return content.size();
}
@Override
public void onBindViewHolder(ImageButtonHolder buttonHolder, int pos) {
}
@Override
public ImageButtonHolder onCreateViewHolder(ViewGroup arg0, int arg1) {
ImageButton b = new ImageButton(mContext);
b.setBackgroundColor(Color.RED);
ImageButtonHolder holder = new ImageButtonHolder(b);
return holder;
}
}
public class ImageButtonHolder extends RecyclerView.ViewHolder {
public final ImageButton imageButton;
public ImageButtonHolder(ImageButton button) {
super(button);
imageButton = button;
}
}
【问题讨论】:
-
sth 在您的 ContentAdapter 中非常错误。每次 RV 需要新视图时,您都会增加
num,当调用getItemCount()时,您将返回num.get()。这是两个不相关的事情。onCreateViewHolder(ViewGroup parent, int type),这里的第二个参数是视图的类型。创建新视图不应更改适配器大小。您可以查看here,例如 RV 使用情况。 -
好吧,一开始我并不认为它会是相关的。所以,我编辑了。
标签: android android-recyclerview