RecyclerView getLayoutParams returns null (sometimes)
I have a RecyclerView for which I have a custom adapter and I have set the LayoutManager as FlexboxLayoutManager. For each child, I want to set FlexGrow to 1.
In Google example, demo-cat-gallery ( https://github.com/google/flexbox-layout ), they do this in the ViewHolder:
void bindTo(Drawable drawable) {
mImageView.setImageDrawable(drawable);
ViewGroup.LayoutParams lp = mImageView.getLayoutParams();
if (lp instanceof FlexboxLayoutManager.LayoutParams) {
FlexboxLayoutManager.LayoutParams flexboxLp = (FlexboxLayoutManager.LayoutParams) lp;
flexboxLp.setFlexGrow(1.0f);
}
}
Then it is called by RecyclerView.Adapter in onBindViewHolder. This works great, but when I did the same in my application, for some elements it will only be setFlexGrow and never at the top. I realized that for some elements (seemingly accidentally) getLayoutParams () returned null, but for others it was returning the correct FlexboxLayoutManager.LayoutParams.
I figured out that the difference is that in the Cat-gallery example onCreateViewHolder was doing
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.viewholder_cat, parent, false);
return new CatViewHolder(view);
}
while in my application i was doing
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
return new MyViewHolder(new MyCustomView(getContext()));
}
It seems that bloating with a parent reference means getLayoutParams () is never null, so changed my code to
View v = new MyCustomView(getContext());
parent.addView(v);
return new MyViewHolder(v);
And now it works correctly, setFlexGrow () is always set. However, this seems to be wrong - I know you shouldn't explicitly add views to the parent of the RecyclerView.
So my question is:
1 - Why is LayoutParams randomly null for some elements, but fine for others?
2 - How can I get LayoutParams to always be asked without doing something terrible like "parent.addView (v);", or is this really ok?
Thank:)
source to share