Android ScrollView 嵌套有ListView控件,ListView只顯示一行數據問題。

在實際開發過程中,經常會碰到ScrollView中嵌套ListView的情景。

可是如果直接使用ScrollView嵌套ListView的話,我們會發現,ListView只能顯示一行。

所以需要動態計算ListView 高度,如下代碼:

    private HomeAdapter adapter;
    private List<GoodsBean> goods;
    private ListView ll_goods;
    ll_goods = view.findViewById(R.id.ll_goods);
    adapter = new HomeAdapter(getContext());
    goods = new ArrayList<>();
    goods.add(new GoodsBean("百仙草1",300f,"含有人體所需的【葉綠素】","權益積分 9000"));
    goods.add(new GoodsBean("百仙草2",300f,"含有人體所需的【葉綠素】","權益積分 9000"));
    goods.add(new GoodsBean("百仙草3",300f,"含有人體所需的【葉綠素】","權益積分 9000"));

    adapter.setDataList(goods);
    ll_goods.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    int totalHeight = 0;
    for (int i = 0, len = adapter.getCount(); i < len; i++) {
         // listAdapter.getCount()返回數據項的數目
         View listItem = adapter.getView(i, null, ll_goods);
        // 計算子項View 的寬高
        listItem.measure(0, 0);
        // 統計所有子項的總高度
        totalHeight += listItem.getMeasuredHeight();
     }
ViewGroup.LayoutParams params
= ll_goods.getLayoutParams(); params.height = totalHeight+ (ll_goods.getDividerHeight() * (adapter.getCount() - 1)); // listView.getDividerHeight()獲取子項間分隔符佔用的高度 // params.height最後得到整個ListView完整顯示需要的高度 ll_goods.setLayoutParams(params);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章