0

Is there any way I can adjust listview's height as of it's content height in xamarin.forms? I could successfully do it for ios but for android, I applied a solution that leads to slow layout rendering.

code

public class CustomListViewRenderer : ListViewRenderer
{

...

protected async override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        base.OnMeasure(widthMeasureSpec, heightMeasureSpec);

        if(Element == null || ((CustomListView)Element).IsScrollable)
        {
            return;
        }

        var view = (CustomListView)Element;
        if(!view.IsScrollable)
        {
            var mAdapter = nativeList.Adapter;

            int totalHeight = 0;
            int listWidth = nativeList.MeasuredWidth;

            int listHeight = nativeList.MeasuredHeight;

            if(totalCount == nativeList.Count)
            {
                //return;
            }

            for (int i = 0; i < mAdapter.Count; i++)
            {
                global::Android.Views.View mView = mAdapter.GetView(i, null, nativeList);

                mView.Measure(MeasureSpec.MakeMeasureSpec(listWidth, MeasureSpecMode.Exactly),
                              MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified));

                totalHeight += (int)(mView.MeasuredHeight / Resources.DisplayMetrics.Density);

                totalCount = i + 1;
            }

            ViewGroup.LayoutParams param = nativeList.LayoutParameters;
            param.Height = totalHeight
                + (nativeList.DividerHeight * (mAdapter.Count - 1));

            view.HeightRequest = param.Height;
        }
    }
    }

This however does not always generate exact height for listview, sometimes leaving space at bottom. Moreover it creates a great delay in laying out the page where list view has been used.

Can anyone please help me with this?

Vishal Vaishnav
  • 3,346
  • 3
  • 26
  • 57
Dhruv Bhagat
  • 33
  • 1
  • 9

1 Answers1

0

Is there any way I can adjust listview's height as of it's content height in xamarin.forms?

You could using HasUnevenRows property to implement this feature :

  • HasUnevenRows – true/false value, rows have varying heights if set to true. Defaults to false.

Row heights don't have to be manually set once HasUnevenRows has been set to true, because the heights will be automatically calculated by Xamarin.Forms.

C# :

RowHeightDemoListView.HasUnevenRows = true;

XAML :

<ListView x:Name="RowHeightDemoListView" HasUnevenRows="true" />
Grace Feng
  • 16,564
  • 2
  • 22
  • 45