Since Google launched Recyclerview has been respected, but I found in practice recyclerview in fact there are many pits, for example, Auto_fit attributes. The
is known to have a Auto_fit attribute and ColumnWidth property in the GridView, when we select Auto_ When fit is true, filling in the width of the columnwidth allows the GridView to automatically calculate the number of columns based on the width of each column, which is adaptive.
come back and we'll see Recylerview. It is well known that recyclerview to implement a grid view is to set the Gridlayoutmanager object, and when we initialize the Gridlayoutmanager object, we set the number of rows or columns of Recyclerview. In this case, it is very troublesome to use it when it is easy to change the width of the window, so what is the best solution?
Careful analysis, the GridView so-called adaptive width to calculate the number of columns is based on the GridView current width and column width to dynamically calculate the layout of the implementation. Then Recyclerview can, of course, follow the same implementation:
public class Autofitrecyclerview extends Recyclerview {private Gridlayoutmanager manager;
The default is-1 private int mcolumnwidth =-1;
Public Autofitrecyclerview (Context context) {super (context);
Init (context);
} public Autofitrecyclerview (context context, AttributeSet Attrs) {Super (context, attrs);
Init (context); } public Autofitrecyclerview (context context, AttributeSet attrs, int defstyle) {Super (context, Attrs, defst
YLE);
Init (context);
} private void Init (context context) {manager = new Gridlayoutmanager (context, 1, VERTICAL, false);
Setlayoutmanager (manager);
} public void Setcolumnwidth (int columnWidth) {mcolumnwidth = ColumnWidth; } @Override protected void onmeasure (int widthspec, int heightspec) {super.onmeasure (Widthspec, HEIGHTSP
EC); if (Mcolumnwidth > 0) {int spancount = Math.max (1, getmeasuredwidth ()/Mcolumnwidth);
Manager.setspancount (Spancount); }
}
}
The code is very simple, by calling the Init () method in the constructor to construct a vertical layout of the Gridlayoutmanager, and then providing a setcolumnwidth interface to set the width of each column, Then in the onmeasure to calculate the number of columns and then set to LayoutManager. This realizes the Auto_fit function, but also encapsulates the Recyclerview with the LayoutManager, making the external invocation more convenient. Let's look at the effect:
Simple dozens of lines of code to achieve our expected effect, of course, this is just a demo, provide a solution to the idea, of course, I also hope to see a better solution.