RecyclerView的自适应高度

RecyclerView一般用来全屏显示是最好的,不过有的时候我们也需要用它来做九宫格等控件,这个时候不得不用到自适应高度来显示这部分了!


其实只要我们在装载完成它的数据集之后,在自定义的LayoutManager中监听它的子控件的高度就可以了~!效果如图:

RecyclerView的自适应高度_第1张图片



这张图的中间部分就是使用的RecyclerView自适应高度来做的!

下面是Manager的自定义:

package com.cq.cake.util;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ViewTreeObserver;

import com.cq.cake.adapter.WeatherAdapter;

/**
 * Created by Small Cake on 2015/12/24.
 * 复写GridLayoutManager的onMeasure动态设置RecyclerView的高度
 */
public class ItemGridLayoutManager extends GridLayoutManager {
    WeatherAdapter adapter;
    TypedArray a;
    Drawable mDivider;
    ViewTreeObserver obs;

    /**
     * @param context      上下文
     * @param spanCount    列数
     * @param adapter      数据适配器
     * @param recyclerView 当前的RecyclerView
     */
    public ItemGridLayoutManager(Context context, int spanCount, WeatherAdapter adapter, final RecyclerView recyclerView) {
        super(context, spanCount);
        this.adapter = adapter;
        a = context.obtainStyledAttributes(new int[]{android.R.attr.listDivider});
        mDivider = a.getDrawable(0);
        obs = recyclerView.getViewTreeObserver();
        obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                calculeRecyclerViewFullHeight(recyclerView);
                obs.removeOnPreDrawListener(this);
                return true;
            }
        });
    }

    /**
     * 刷新高度,使RecyclerView得高度为wrap_content
     */
    private void calculeRecyclerViewFullHeight(RecyclerView recyclerView) {
        int height = 0;
        height = recyclerView.getChildAt(0).getHeight();
        int line = adapter.getItemCount() / getSpanCount();
        if (adapter.getItemCount() % getSpanCount() > 0) {
            line++;
        }
        SwipeRefreshLayout.LayoutParams params = recyclerView.getLayoutParams();
        params.height = height * line + (line - 1) * mDivider.getIntrinsicWidth();
        recyclerView.setLayoutParams(params);

    }

}
希望对需要做自适应高度的同学有所帮助,使用的时候

mRecyclerView.setLayoutManager(new ItemGridLayoutManager(this, 3, adapter, mRecyclerView));

缺点就是参数太多了,希望厉害的大神帮忙改进~!


你可能感兴趣的:(Android,Android)