public static class GridAutofitLayoutManager extends GridLayoutManager {
private int mColumnWidth;
private boolean mColumnWidthChanged = true;
public GridAutofitLayoutManager(Context context, int columnWidth) {
super(context, 1);
setColumnWidth(checkedColumnWidth(context, columnWidth));
}
public GridAutofitLayoutManager(Context context, int columnWidth,int orientation, boolean reverseLayout) {
/* Initially set spanCount to 1, will be changed automatically later. */
super(context, 1, orientation, reverseLayout);
setColumnWidth(checkedColumnWidth(context, columnWidth));
}
private int checkedColumnWidth(Context context, int columnWidth) {
if (columnWidth <= 0) {
/* Set default columnWidth value (48dp here). It is better to move this constant
to static constant on top, but we need context to convert it to dp, so can'treally do so. */
columnWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,48, context.getResources().getDisplayMetrics());
}
return columnWidth;
}
public void setColumnWidth(int newColumnWidth) {
if (newColumnWidth > 0 && newColumnWidth != mColumnWidth) {
mColumnWidth = newColumnWidth;
mColumnWidthChanged = true;
}
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler,RecyclerView.State state) {
if (mColumnWidthChanged && mColumnWidth > 0) {
int totalSpace;
if (getOrientation() == VERTICAL) {
totalSpace = getWidth() - getPaddingRight() - getPaddingLeft();
} else {
totalSpace = getHeight() - getPaddingTop() - getPaddingBottom();
}
int spanCount = Math.max(1, totalSpace / mColumnWidth);
setSpanCount(spanCount);
mColumnWidthChanged = false;
}
super.onLayoutChildren(recycler, state);
}
}
출처 : https://codentrick.com/part-4-android-recyclerview-grid/
'Android' 카테고리의 다른 글
[Android] 안드로이드 폴더 내 파일 리스트 가져오기 (0) | 2016.11.14 |
---|---|
Android recyclerView state save 안드로이드 리사이클러뷰 상태 저장 (onSaveInstanceState, onRestoreInstanceState) (1) | 2016.11.09 |
[Android] 안드로이드 Toolbar menu 버튼 만들기 (0) | 2016.11.07 |
[Android] 안드로이드 커스텀 네비게이션 드로어 만들기(Custom Navigation Drawer) (0) | 2016.11.03 |
[Android] 안드로이드 디바이스 해상도별 레이아웃 대응 라이브러리(ScalableLayout) (0) | 2016.11.03 |