1

在我的应用程序中,我使用的是 StaggeredGridView,它工作正常。但是当我将它放在一个 scorllview 中并尝试滚动它时,不幸的是 StaggeredGridView 的高度与确切的网格视图不匹配。

为了控制滚动,我正在动态计算网格视图的高度,并通过基于子项以编程方式将其设置为网格视图。我认为这将是问题..

这里的主要问题是项目高度与普通网格视图不同。

这是我的 setGridViewHeightBasedOnChildren 代码

public static void setListViewHeightBasedOnChildren(StaggeredGridView listView) {

SampleAdapter listAdapter = (SampleAdapter) listView.getAdapter();
if (listAdapter == null)
    return;

int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;

for (int i = 0; i < listAdapter.getCount(); i++) {
    view = listAdapter.getView(i, view, listView);
    if (i == 0)
        view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, LayoutParams.WRAP_CONTENT));

    view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
    totalHeight += view.getMeasuredHeight();
}

ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getHeight() * (listAdapter.getCount() - 1));

listView.setLayoutParams(params);
listView.requestLayout();
  }

任何人都可以帮我在滚动视图中放置一个 StaggeredGridView.. 在此先感谢

4

1 回答 1

0

尝试使用下面的代码并传递 no of column :

public void setListViewHeightBasedOnChildren(StaggeredGridView staggeredGridView, int columns) {
        SampleAdapter listAdapter = (SampleAdapter) staggeredGridView.getAdapter(); 
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        int items = listAdapter.getCount();
        int rows = 0;

        View listItem = listAdapter.getView(0, null, staggeredGridView);
        listItem.measure(0, 0);
        totalHeight = listItem.getMeasuredHeight();

        float x = 1;
        if( items > columns ){
            x = items/columns;
            rows = (int) (x + 1);
            totalHeight *= rows;
        }

        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        params.height = totalHeight;
        gridView.setLayoutParams(params);

}
于 2015-10-30T10:13:08.963 回答