Xamarin Forms (2)


Xamarin ListView performance & replacing it with Syncfusion SfListView

While Xamarin keeps adding features and improves the performance of Xamarin Forms with each and every update, what they offer in terms of cross-platform user controls is not always enough. In my case, I’ve got an RSS reader app which aggregates news articles from different sources and displays them in a ListView like this:

Gazeta Xamarin ListView

While I like how the app looks, it has a big issue – performance. Even on high-end devices the scrolling is sluggish and on low-end devices it keeps on throwing OutOfMemory exceptions due to the images that are being loaded. So, a change was needed. In this article I’ll only cover the first one – the scrolling performance; we’ll have a look at the OutOfMemory exceptions another time.

The Item template

First thing you need to look at when troubleshooting performance is the ListView ItemTemplate. Any kind of optimization that you can do at this level will have a big impact on the overall performance of your ListView. Look at things like:

  • reducing the number of XAML elements. The fewer elements to render, the better
  • same goes for nesting. Avoid nesting elements and creating deep hierarchies. It will take way too long to render them
  • make sure your ItemSource is an IList and not an IEnumerable collection. IEnumerable doesn’t support random access
  • don’t change the layout based on your BindingContext. Use a DataTemplateSelector instead

You should already see some improvements in scrolling after making these changes. Next on the list is your caching strategy.

Caching strategy

By default Xamarin uses the RetainElement caching strategy for Android and iOS which means that it will create one instance of your ItemTemplate for each item in your list. Change your ListView’s caching strategy to RecycleElement to reuse containers that are no longer in view instead of creating new elements every time. This will increase performance by removing initialization costs.

<ListView CachingStrategy="RecycleElement">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
              ...
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

If by any chance you’re using a DataTemplateSelector, then you should use the RecycleElementAndDataTemplate caching strategy. For more details on caching strategies you can check Xamarin’s documentation on ListView performance.

Syncfusion ListView

If you got this far and your performance issues aren’t solved, then it’s time looking at other options. In my case, I gave Syncfusion SfListView a try because they’re known for their control suites and they offer their Xamarin controls for free under the same conditions as Visual Studio Community (more or less). To get started head over to Syncfusion’s website an claim your free comunity license if you haven’t already.

Next, you need to add the SfListView package to your project. Syncfusion packages are available through their own NuGet repository. To be able to access it you’ll need to add it to you NuGet sources. A complete guide on how to do that can be found here. One you’ve done that, a simple search for SfListView in NuGet will result in the desired package. Install the package in your core/cross-platform project and in all your platform projects as well; it will automatically pick up the correct DLLs based on your project’s target.

Now that you’ve got everything installed, it’s time to replace the standart ListView. To do so, add the following namespace in your page/view:

xmlns:sflv="clr-namespace:Syncfusion.ListView.XForms;assembly=Syncfusion.SfListView.XForms"

And then replace the ListView tag with sflv:ListView, the ListView.ItemTemplate with sflv:SfListView.ItemTemplate and remove the ViewCell from your hierarchy – it’s not needed. Additionaly, if you’ve been using the CachingStrategy property, remove that as well – SfListView recycles elements by default. You should end up with something like this:

<sflv:ListView>
    <sflv:SfListView.ItemTemplate>
        <DataTemplate>
           ...
        </DataTemplate>
    </sflv:SfListView.ItemTemplate>
</sflv:SfListView>

That’s it. If you have any questions let me know in the comments section below. Also, if you’ve got any other tips to share that would improve ListView performance, please do.




How To: Add AdMob to your Xamarin Forms app

One of the first things people think about when developing for a new platform / using a new technology is monetization; and in my case the question is: how easy is it to integrate AdMob? For Xamarin Forms the answer would be: “It depends” – it depends on luck & on the complexity of what you want to achieve; but I will detail this as we move along.

The first thing you need to do is add the required components to your projects. For this walktrough I will be using Visual Studio but it should be relatively the same when using Xamarin Studio. Here, things go separate ways for each of the platforms:

  • for Android – add the Google Play Services component
  • for iOS – add the AdMob component
  • for Windows Phone – download the SDK from here and add it as a reference

By now, you Android project should no longer be building & you should be receiving a COMPILETODALVIK : UNEXPECTED TOP-LEVEL error. To fix that, go into your Droid project properties, select the Android Options tab and then under Advanced modify the value for the Java Max Heap Size to 1G. Your project should now build without any errors.

Next, inside your shared / PCL project add a new Content View and call it AdMobView. Remove the code generated inside it’s constructor & it should look like this:

public class AdMobView : ContentView
{
    public AdMobView() { }
}

Add this new view to your page. In XAML you can do it like this:

<controls:AdMobView WidthRequest="320" HeightRequest="50" />

Make sure NOTHING interferes with the control. By nothing I mean – overlapping controls, page padding, control margins / spacing, etc. If you have something overlapping the ad control, ads will not display & you won’t receive an error, so be careful.

Next, it’s time to add the custom view renderers; and again, we’ll handle each platform:

Android

Add a new class called AdMobRenderer with the code below. Make sure to keep the ExportRenderer attribute above the namespace, otherwise the magic won’t happen.

[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobRenderer))]

namespace AdExample.Droid.Renderers
{
    public class AdMobRenderer : ViewRenderer<AdMobView, Android.Gms.Ads.AdView>
    {
        protected override void OnElementChanged(ElementChangedEventArgs<AdMobView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var ad = new Android.Gms.Ads.AdView(Forms.Context);
                ad.AdSize = Android.Gms.Ads.AdSize.Banner;
                ad.AdUnitId = "_your_admob_ad_unit_id_goes_here_";

                var requestbuilder = new Android.Gms.Ads.AdRequest.Builder();
                ad.LoadAd(requestbuilder.Build());

                SetNativeControl(ad);
            }
        }
    }
}

Next, you need to modify your AndroidManifest.xml file to add the AdActivity & required permissions for displaying ads: ACCESS_NETWORK_STATE, INTERNET; just like in the example below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
	<uses-sdk android:minSdkVersion="15" />
	<application>
    <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
  </application>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.INTERNET" />
</manifest>

That’s it. Your Android build should now display ads inside the AdMobView content view.

Windows Phone

Just like for Android, add a new class to your WinPhone project called AdMobRenderer having the code below.

[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobRenderer))]

namespace AdExample.WinPhone.Renderers
{
    public class AdMobRenderer : ViewRenderer<AdMobView, GoogleAds.AdView>
    {
        protected override void OnElementChanged(ElementChangedEventArgs<AdMobView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var ad = new GoogleAds.AdView();
                ad.Format = AdFormats.Banner;
                ad.AdUnitID = "_your_admob_ad_unit_id_goes_here_";

                var adRequest = new GoogleAds.AdRequest();
                ad.LoadAd(adRequest);

                SetNativeControl(ad);
            }
        }
    }
}

iOS

This, I haven’t got the chance to test yet as I don’t have a Mac around but people say it works, so I’ve added it for reference. Same as before, just add a new class called AdMobRenderer and copy-paste the code below.

[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobRenderer))]

namespace GazetaSporturilor.iOS.Renderers
{
    public class AdMobRenderer : ViewRenderer
    {
        const string AdmobID = "_your_admob_ad_unit_id_goes_here_";

        GADBannerView adView;
        bool viewOnScreen;

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement == null)
                return;

            if (e.OldElement == null)
            {
                adView = new GADBannerView(GADAdSizeCons.SmartBannerPortrait)
                {
                    AdUnitID = AdmobID,
                    RootViewController = UIApplication.SharedApplication.Windows[0].RootViewController
                };

                adView.AdReceived += (sender, args) =>
                {
                    if (!viewOnScreen) this.AddSubview(adView);
                    viewOnScreen = true;
                };

                GADRequest request = GADRequest.Request;

                adView.LoadRequest(request);
                base.SetNativeControl(adView);
            }
        }
    }
}

That’s it. Now you have ads being served on all platforms. Any comments or suggestions you have leave them in the comments section below.