2020.09.01.

Xamarin.Android – Automatic ListView Height

By bence960206

We all use lists in our apps. But it doesn’t matter how it appears. Here now it’s not going to be about having a list and exposing it to a page and just going to be there, but there’s more of everything on a page and you don’t want to have a certain height and be able to scroll through a small area but be as high as there are elements in it.

First step: create a Xamarin.Android Project.

Add a ListView to your layout’s xml:

           <ListView
                android:id="@+id/someListView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:divider="@android:color/transparent"
                android:scrollbars="none"
                android:listSelector="@android:color/transparent"
                android:background="@android:color/transparent"/>

I’m just using transparent colors (divider – separatorcolor, listSelector – selected item’s color and the view’s background as well).

After that we have to implement some code behind code in our MainAcitivty (or whatever you wanted to use):

        /// <summary>
        /// Fully scale your ListView.
        /// </summary>
        /// <param name="listView">ListView, that you want to scale fully.</param>
        public void SetListViewAutomaticHeight(ListView listView)
        {
            int totalHeight = 0;
            for (int i = 0; i < listView.Adapter.Count; i++)
            {
                View listItem = listView.Adapter.GetView(i, null, listView);
                listItem.Measure(0, 0);
                totalHeight += listItem.MeasuredHeight;
            }

            ViewGroup.LayoutParams paramss = listView.LayoutParameters;
            paramss.Height = totalHeight + (listView.DividerHeight * (listView.Adapter.Count - 1));
            listView.LayoutParameters = paramss;
            listView.RequestLayout();
        }

And after, if you added the adapter to your ListView you have to call this function and add his parameter to your ListView:

            ListView someListView = (ListView)view.FindViewById(Resource.Id.someListView);
            someListView .Adapter = new SomeAdapter(someList);

            SetListViewAutomaticHeight(someListView );

And this will scale your ListView automatically. If your list is updated, you have to call this function again.