Kartik
Kartik

Reputation: 7907

RecyclerView's size doesn't change after setting adapter

In a fragment, I set layout manager on a RecyclerView in onActivityCreated:-

galleryRecView.setLayoutManager(new LinearLayoutManager(getActivity()));

Then I execute an AsyncTask, which downloads the data to be set in the RecyclerView.

Now I set the adapter on my RecyclerView:-

public void onPhotosURLsReceived(boolean success) {
    if (success && isAdded())
        galleryRecView.setAdapter(new GalleryAdapter(getActivity(), Constants.photosList));
}

The problem:-

The RecyclerView's layout_height is set to wrap_content. So in the starting, when there is no adapter set on the RecyclerView, it takes a height of 0dp. When I set the adapter after the AsyncTask is over, it still remains at 0dp and nothing can be seen. This was never a problem with ListView.

Note:-

After I get this list working, I am planning to convert it to a non-scroll RecyclerView to use inside a scrollView and swipeLayout by extending RecyclerView and overriding onMeasure like this:-

public class NonScrollRecyclerView extends RecyclerView {

public NonScrollRecyclerView(Context context) {
    super(context);
}

public NonScrollRecyclerView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public NonScrollRecyclerView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

 /*
 *  Non-scroll listview to use with SwipeRefreshLayout and scrollview
 */

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
            Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
    ViewGroup.LayoutParams params = getLayoutParams();
    params.height = getMeasuredHeight();
}
}

Upvotes: 1

Views: 1065

Answers (1)

Kartik
Kartik

Reputation: 7907

Turns out that RecyclerView inside a ScrollView was a problem.

I removed the ScrollView and put the content which was outside the RecyclerView, inside the RecyclerView as another view type by overriding getItemViewType(int position).

This not only solved the problem, it also got rid of the need for a non-scroll RecyclerView. A non-scroll RecyclerView would not recycle views and the purpose of it would be defeated.

Upvotes: 2

Related Questions