ScrollView嵌套ListView、RecyclerView,使其高度自適應(yīng)

最終效果

今天在制作一個頁面,思路是這樣的:整個布局以ScrollView進行嵌套,布局里面包含ListView和RecyclerView。點擊“TA的語錄”按鈕,則呈現(xiàn)ListView列表,此時RecyclerView設(shè)置不可見,點擊“TA的筆記”按鈕,則呈現(xiàn)RecyclerView列表,此時ListView設(shè)置不可見。
然而在測試時發(fā)現(xiàn)ListView和RecyclerView都顯示不完整,高度無法完全展開......于是上網(wǎng)查了下資料。接下來分享兩個我覺得最簡單的解決方法吧 > <

1、針對ScrollView嵌套ListView時只顯示第一個item高度的bug,可在activity里動態(tài)修改ListView的高度(即計算每個item和分割線的高度后進行相加得到總高度),在setAdapter之后調(diào)用下面這個函數(shù)即可。
值得注意的是,此時ListView的子item根布局應(yīng)設(shè)為LinearLayout。

 private void setListViewHeightBasedOnChildren(ListView listView) {
      if (listView == null) {
          return;
      }
      ListAdapter listAdapter = listView.getAdapter();
      if (listAdapter == null) {
          return;
      }
      int totalHeight = 0;
      for (int i = 0; i < listAdapter.getCount(); i++) {
          View listItem = listAdapter.getView(i, null, listView);
          listItem.measure(0, 0);
          totalHeight += listItem.getMeasuredHeight();
      }
      ViewGroup.LayoutParams params = listView.getLayoutParams();
      params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
      listView.setLayoutParams(params);
  }

2、針對ScrollView嵌套RecyclerView時顯示不完整的bug,直接在RecyclerView外嵌套一層RelationLayout即可解決。

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:focusable="false"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>
</RelativeLayout>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容