Android 具有不同大小正方形的GridLayout显示不正确
我正试图使这个GridLayout正确显示,但由于某些原因它不起作用 这就是我所拥有的和我想要的: 这是我的密码:Android 具有不同大小正方形的GridLayout显示不正确,android,android-recyclerview,android-gridlayout,Android,Android Recyclerview,Android Gridlayout,我正试图使这个GridLayout正确显示,但由于某些原因它不起作用 这就是我所拥有的和我想要的: 这是我的密码: GridLayoutManager lm = new GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false); mCustomView.setLayoutManager(lm); mCustomAdapter = new CustomAdapter(imagesList); mCustomView.setA
GridLayoutManager lm = new GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false);
mCustomView.setLayoutManager(lm);
mCustomAdapter = new CustomAdapter(imagesList);
mCustomView.setAdapter(mCustomAdapter);
这在CustomAdapter中的OnCreateViewHolder下
itemView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
@Override
public void onGlobalLayout() {
final GridLayoutManager lm = (GridLayoutManager) ((RecyclerView) parent).getLayoutManager();
lm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
int mod = position % 4;
if(mod == 1 || mod == 2)
return 1;
else
return 2;
}
});
int pLength = itemView.getWidth();
ViewGroup.LayoutParams pParams = itemView.getLayoutParams();
pParams.width = pLength;
pParams.height = pLength;
itemView.setLayoutParams(pParams);
itemView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
如果对这个问题有任何疑问,或者您需要更多信息,我很乐意提供:)
谢谢。我认为,您可以使用“自定义视图”来包装项目视图。在“自定义视图”中,您应该在“测量方法”上覆盖
:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// set your width and height
setMeasuredDimension(width, height);
}
另一个想法
创建layoutManager
时:
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if( position % 4 == 1 || position %4 ==2)
return 1;
else
return 2;
}
});
经理将自动设置每个项目的宽度和高度,这样您就不用手动设置了。经过近一周的努力,我找到了解决办法。我在这样的事情上浪费了一个星期,真是太愚蠢了,但事实就是这样。在CustomAdapter中调用OnCreateViewHolder中的函数setPansizeLookup(),而不是在调用适配器时调用该函数
GridLayoutManager lm = new GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false);
lm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
int mod = position % 4;
if(mod == 1 || mod == 2)
return 1;
else
return 2;
}
});
mCustomView.setLayoutManager(lm);
mCustomAdapter = new CustomAdapter(imagesList);
mCustomView.setAdapter(mCustomAdapter);
这修复了未知原因的错误
注意:尽管科尔提出了几乎相同的建议,但这与问题的背景无关。如果他先阅读了我当前的代码,他本可以正确回答我的问题。我没有固定的宽度或高度。我希望它使用GridLayout跨度中的所有可用宽度。您的项目的宽度和高度是随机的?它是一个3列的GridLayout,如问题中所示,第一个元素将占用2列跨度,下一个元素将占用1列跨度。这很简单。首先,您可以获得GridLayout的宽度,然后在RV适配器中设置两个子元素的宽度。您是否忘记了位置
=0?我怀疑您可能无法获得所需的精确布局。你所展示的这个图表需要一个高度是其宽度2倍的设备。典型的纵横比更像1.6。我认为您看到的是,在布局过程中,较小的面板受到限制,以使它们全部显示在屏幕上(由于面板1只能是半高,因此也被限制为半宽)。不,不,不,问题是由于某种原因,只有第一个元素(位置=0)显示错误(可以在图表中看到)。之后它会正确显示。