How can I put a ListView into a ScrollView without it collapsing?

后端 未结 27 3232
轮回少年
轮回少年 2020-11-21 05:24

I\'ve searched around for solutions to this problem, and the only answer I can find seems to be \"don\'t put a ListView into a ScrollView\". I have yet to see any real expl

27条回答
  •  清酒与你
    2020-11-21 06:00

    I converted @DougW's Utility into C# (used in Xamarin). The following works fine for fixed-height items in the list, and is going to be mostly fine, or at least a good start, if only some of the items are a bit bigger than the standard item.

    // You will need to put this Utility class into a code file including various
    // libraries, I found that I needed at least System, Linq, Android.Views and 
    // Android.Widget.
    using System;
    using System.Linq;
    using Android.Views;
    using Android.Widget;
    
    namespace UtilityNamespace  // whatever you like, obviously!
    {
        public class Utility
        {
            public static void setListViewHeightBasedOnChildren (ListView listView)
            {
                if (listView.Adapter == null) {
                    // pre-condition
                    return;
                }
    
                int totalHeight = listView.PaddingTop + listView.PaddingBottom;
                for (int i = 0; i < listView.Count; i++) {
                    View listItem = listView.Adapter.GetView (i, null, listView);
                    if (listItem.GetType () == typeof(ViewGroup)) {
                        listItem.LayoutParameters = new LinearLayout.LayoutParams (ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
                    }
                    listItem.Measure (0, 0);
                    totalHeight += listItem.MeasuredHeight;
                }
    
                listView.LayoutParameters.Height = totalHeight + (listView.DividerHeight * (listView.Count - 1));
            }
        }
    }
    

    Thanks @DougW, this got me out of a tight spot when I had to work with OtherPeople'sCode. :-)

提交回复
热议问题