Ashkan Ashkan - 1 year ago 131
Android Question

Use RecyclerView inside ScrollView with flexible Recycler item height

I want to know is there any possible way to use RecyclerView?

before this I use RecyclerView with fix height inside a ScrollView but this time i don't know height of the item.

Hint: I read all question and solution of stack question before ask this question since 4 days ago.

some solution learn how to scroll RecyclerView on his own but i want to show this expanded.

Answer Source

I search for answer this question all over the word but I didn't fount any direct answer for this popular question. At last I mix some trick together and solve this problem!

My problem start when my boss asked me to use a RecyclerView inside a ScrollView, and as you know we cannot use two Scrollable object inside each other except when we set or know fix item height for our RecyclerView. and this is the answer:

Step 1: at first you should find your RecyclerView flexible item height and this is possible from your RecyclerView>onBindViewHolder Runnable() {
        public void run() {

            int cellWidth = holder.itemView.getWidth();// this will give you cell width dynamically
            int cellHeight = holder.itemView.getHeight();// this will give you cell height dynamically

            dynamicHeight.HeightChange(position, cellHeight); //call your iterface hear

with this code you find your item height as them build and send the item height to your activity with interface.

for those friend who have problem with interface i live interface code below that should write in Adapter.

public interface DynamicHeight {
    void HeightChange (int position, int height);

Step 2: we found our item height so far and now we want to set height to our RecyclerView. first we should calculate the Summation of item height. in this step we do this by BitMap first implements last step interface and write these code below inside your Activity or Fragment that define your RecyclerView:

public void HeightChange(int position, int height) {
    itemHeight.put(position, height);
    sumHeight = SumHashItem (itemHeight);

    float density = activity.getResources().getDisplayMetrics().density;
    float viewHeight = sumHeight * density;
    review_recyclerView.getLayoutParams().height = (int) sumHeight;

    int i = review_recyclerView.getLayoutParams().height;

int SumHashItem (HashMap<Integer, Integer> hashMap) {
    int sum = 0;

    for(Map.Entry<Integer, Integer> myItem: hashMap.entrySet())  {
        sum += myItem.getValue();

    return sum;

Step 3: now we have the summation of your RecyclerView height. for last step we should just send the Interface that we write in last step to adapter with some code like this:

reviewRecyclerAdapter = new ReviewRecyclerAdapter(activity, reviewList, review_recyclerView, this);

when you implement interface, you should send it to your with your context that I use this.

Enjoy it