2016-05-04 28 views
0

我遇到了一個問題,源於Android對嵌套滾動元素有一定的困難。計算初始生命週期中的ExpandableListView高度

我有承載水平RecyclerView,只是它下面的ExpandableListView滾動型。 我遇到的問題是ScrollView沒有滾動。 1.設置固定的高度到RecyclerView:

我通過固定它。 2.計算ExpandableListView高度,每個組項目點擊。 像這樣:

expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { 

      @Override 
      public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { 
       setListViewHeight(parent, groupPosition); 
       return false; 
      } 
     }); 

private void setListViewHeight(ExpandableListView listView, int group) { 
     ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter(); 
     int totalHeight = 0; 
     int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(),View.MeasureSpec.EXACTLY); 
     for (int i = 0; i < listAdapter.getGroupCount(); i++) { 
      View groupItem = listAdapter.getGroupView(i, false, null, listView); 
      groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED); 

      totalHeight += groupItem.getMeasuredHeight(); 

      if (((listView.isGroupExpanded(i)) && (i != group)) || ((!listView.isGroupExpanded(i)) && (i == group))) 
      { 
       for (int j = 0; j < listAdapter.getChildrenCount(i); j++) 
       { 
        View listItem = listAdapter.getChildView(i, j, false, null,listView); 
        listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED); 
        totalHeight += listItem.getMeasuredHeight(); 
       } 
      } 
     } 

     ViewGroup.LayoutParams params = listView.getLayoutParams(); 
     int height = totalHeight + (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1)); 
     if (height < 10) 
      height = 200; 
     params.height = height; 
     listView.setLayoutParams(params); 
     listView.requestLayout(); 
    } 

問題: 因爲我只計算在組項目點擊ListView的高度,當我剛打開片段,直到我點擊了一批項目,了滾動不起作用。 我發現在onCreateView中計算ExpandableListView適配器的高度是有問題的,因爲它在那時仍然是空的。

任何想法都會大大降低。

回答

1

如果您需要等到視圖佈局完成,則可以使用 a ViewTreeObserver。例如:

protected void onCreate(Bundle savedInstanceState) { 

    ... 

    final View someView = findViewById(R.id.some_id); 
    someView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
     public void onGlobalLayout() { 

      // the values are now available 
      int mesuredHeight = someView.getMeasuredHeight(); 
      int height = someView.getHeight(); 

      // done, remove the observer 
      someView.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
     } 
    }); 

    ... 
} 
+0

但它確實影響性能..看來這是調用我每次觸摸屏幕的時間..如果我添加一個if語句,使其只調用該方法的第一次,問題回報。 – BVtp

+0

實際上,偵聽器在無限循環中被調用。甚至沒有觸及 – BVtp

+0

這是爲了避免這種類型的問題,聽衆被刪除。如果您在觸摸視圖之前刪除了偵聽器**,它有幫助嗎? – bwt