Ume*_*ooq 16 android gridlayoutmanager
我正在尝试根据显示大小更改回收器视图(网格布局)中显示的列数.但是我无法找到实现它的正确方法.目前我正在使用treeViewObserver
根据屏幕大小的变化(在定向期间)更改列数.因此,如果应用程序以纵向模式打开,列数(在手机上)它决定为一个,看起来不错,但当应用程序直接以横向模式打开时,此方法不起作用,其中网格中有单个拉出的卡片显示在屏幕上.
这里recList是RecyclerView&glm是RecyclerView中使用的GridLayoutManager
viewWidth = recList.getMeasuredWidth();
cardViewWidthZZ = recList.getChildAt(0).getMeasuredWidth();
if (oldWidth == 0) {
oldWidth = cardViewWidthZZ;
}
if (oldWidth <= 0)
return;
int newSpanCount = (int) Math.floor(viewWidth / (oldWidth / 1.3f));
if (newSpanCount <= 0)
newSpanCount = 1;
glm.setSpanCount(newSpanCount);
glm.requestLayout();
Run Code Online (Sandbox Code Playgroud)
最好的祝福
jas*_*xir 29
public class VarColumnGridLayoutManager extends GridLayoutManager {
private int minItemWidth;
public VarColumnGridLayoutManager(Context context, int minItemWidth) {
super(context, 1);
this.minItemWidth = minItemWidth;
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler,
RecyclerView.State state) {
updateSpanCount();
super.onLayoutChildren(recycler, state);
}
private void updateSpanCount() {
int spanCount = getWidth() / minItemWidth;
if (spanCount < 1) {
spanCount = 1;
}
this.setSpanCount(spanCount);
}}
Run Code Online (Sandbox Code Playgroud)
chi*_*uki 15
如果提供固定的列宽,则可以相应地扩展RecyclerView
和设置跨度计数onMeasure
:
public AutofitRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
if (attrs != null) {
// Read android:columnWidth from xml
int[] attrsArray = {
android.R.attr.columnWidth
};
TypedArray array = context.obtainStyledAttributes(attrs, attrsArray);
columnWidth = array.getDimensionPixelSize(0, -1);
array.recycle();
}
manager = new GridLayoutManager(getContext(), 1);
setLayoutManager(manager);
}
protected void onMeasure(int widthSpec, int heightSpec) {
super.onMeasure(widthSpec, heightSpec);
if (columnWidth > 0) {
int spanCount = Math.max(1, getMeasuredWidth() / columnWidth);
manager.setSpanCount(spanCount);
}
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅我的博文:http: //blog.sqisland.com/2014/12/recyclerview-autofit-grid.html
归档时间: |
|
查看次数: |
15813 次 |
最近记录: |