2016-07-06 73 views
0

我需要在滾動視圖中實現列表視圖。 我知道在滾動視圖中使用listview並不是個好主意,但它是應用程序的需求,所以我需要實現它。 在應用程序即時使用TabLayout 3種類型的標籤,如類別1,類別2和類別3過濾數據。如何將動態高度設置爲片段活動中的列表視圖..?

第一個標籤類別1我需要添加2個列表視圖一個是固定項目,第二個是動態的。 拳頭列表視圖是固定的,所以我可以給它固定的高度。 但第二個列表視圖是動態的,所以我需要根據列表視圖中的值的總數給出高度。

即時嘗試許多方法來給動態高度,但沒有完成任務。

這裏是我的方法試alredy -

-------------------第一-------------- ----------------- 第一個從問題

Android: How to measure total height of ListView

public static void getTotalHeightofListView(ListView listView) { 

    ListAdapter mAdapter = listView.getAdapter(); 

    int totalHeight = 0; 

    for (int i = 0; i < mAdapter.getCount(); i++) { 
     View mView = mAdapter.getView(i, null, listView); 

     mView.measure(
       View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), 

       View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); 

     totalHeight += mView.getMeasuredHeight(); 
     Log.w("HEIGHT" + i, String.valueOf(totalHeight)); 

    } 

    ViewGroup.LayoutParams params = listView.getLayoutParams(); 
    params.height = totalHeight 
      + (listView.getDividerHeight() * (mAdapter.getCount() - 1)); 
    listView.setLayoutParams(params); 
    listView.requestLayout(); 

} 

----------------- --second ------------------------------- from question https://stackoverflow.com/questions/17693578

public static class ListUtils { 
    public static void setDynamicHeight(ListView mListView) { 
     ListAdapter mListAdapter = mListView.getAdapter(); 
     if (mListAdapter == null) { 
      // when adapter is null 
      return; 
     } 
     int height = 0; 
     int desiredWidth = MeasureSpec.makeMeasureSpec(mListView.getWidth(), MeasureSpec.UNSPECIFIED); 
     for (int i = 0; i < mListAdapter.getCount(); i++) { 
      View listItem = mListAdapter.getView(i, null, mListView); 
      listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED); 
      height += listItem.getMeasuredHeight(); 
     } 
     ViewGroup.LayoutParams params = mListView.getLayoutParams(); 
     params.height = height + (mListView.getDividerHeight() * (mListAdapter.getCount() - 1)); 
     mListView.setLayoutParams(params); 
     mListView.requestLayout(); 
    } 
} 

-------------------錯誤-------------------

+0

像你說的:不要這樣做。我會建議使用另一種方法,或至少爲我們提供當前狀態的截圖。 – finki

+0

好吧我將發佈它 –

回答

0

在你的活動XML文件,你可以使用的LinearLayout滾動型內,然後可以分配機器人:體重屬性給他們。

您可以將權重分配給單個元素和所有其他元素,並調整它們各自的可用空間。

+0

不與重量工作 –

+0

如果你給第一個元素的固定高度,那麼剩餘空間將自動給予第二個元素。如果第二個元素不需要太多的空間,那麼它們下面會留下一些空間。您不必爲列表視圖分配dyanmic空間。它將被自動分配。你可以使用'android:layout_width = wrap_content'。 – Saini

+0

非常感謝 –

0

更好的做法是,它使用支持視圖動態變化的列表。併爲您的問題有特別清單 - LinkedListView

相關問題