Back to Home

Cooking Xamarin.Forms: environment setup and first steps / Microsoft Blog

xamarin · xamarin.forms · ios · android · performance · environment · visual studio · xaml · xamarincolumn

Cooking Xamarin.Forms: setting up the environment and first steps



    Friends! We continue the column on the development of mobile applications on Xamarin. And
    after a short break, we are ready to return to consider the features of using Xamarin.Forms when developing business applications for iOS and Android. All articles from the column can be found and read at #xamarincolumn

    In today's article, we will consider application performance issues and optimizing the development process itself.

    Right bees


    In a wonderful fairy tale about Winnie the Pooh, the bees were divided into right and wrong. Similarly, the environments in which application development will go can be conditionally divided into right and wrong.

    We will start with the computers on which development will go.

    In our practice, we use Windows 10 and Visual Studio 2015 as the main environment, so we encountered the fact that building applications (primarily Android) takes an unacceptably long time.

    We began to find out what was happening here and identified several bottlenecks that slow down development:
    • during the assembly of Android applications, Xamarin can for the first time pump out the necessary source codes for additional components and store them on a local drive for later use. Nothing can be done here, so just be prepared for the fact that the first assembly can take you about 10 minutes.
    • the fun part begins: during the build, Xamarin generates and uses a large number of files (up to 200 MB in the bin and obj folders, plus a whole bunch in the Temp folder), so just forget about using hard disks (HDDs) on workstations - the faster will you have an SSD the better.

    Especially advanced you can recommend the use of RAM as a partition for storing projects and the system Temp folder - for this you need to use one of the RAM Disk class programs. We did not make exact measurements when using SSD + RAM Disk, but the difference is huge by eye.

    So, we believe that we have figured out the right environment.

    Haml - evil or good


    One of the important mechanisms of Xamarin.Forms is the ability to use XAML (XML-based) to describe the user interface.

    In our opinion, this is a good solution from the point of view of production technology, since there is a separation of logic from the description of the interface and the UI development itself becomes very similar to the HTML layout, even control styles can be set in one place as with CSS (educational program by styles on the link ), including a little tuning for different platforms (Device.OnPlatform).

    Everything would be fine, if not for one big “BUT”, which is typical for Xamarin.Forms version 1.x - XAML files were interpreted on the fly, including creating all the necessary controls and placing them on the screen. Because of this, each opening of a new window with a complex layout took longer than we would like.

    In version 2.0, this flaw was eliminated by implementing XAML precompilation. You can use it for individual pages and View on XAML, as well as for the entire project.

    We enable compilation of a separate XAML page (file MainPage.xaml.cs, for example)



    using Xamarin.Forms.Xaml;
    ...
    [XamlCompilation (XamlCompilationOptions.Compile)]
    public class MainPage : ContentPage
    { 
    ...
    }
    


    We activate compilation throughout the project - add a new line to the end of the Properties / AssemblyInfo.cs file in the PCL project:



    ...
    [assembly: XamlCompilation(XamlCompilationOptions.Compile)]
    


    However, in some cases, especially when implementing cells for ListView, it may be more efficient to describe the layout for ViewCell / View / Page with your hands in C # code or go down to the iOS / Android level .



    But we will return to ListView.



    Pictures, icons and performance


    The first thing novice developers at Xamarin.Forms face is sticking when scrolling through lists based on ListView. To be honest, this is one of the painful places on the platform that casts a shadow over the rest of the functionality, since lists are used in large quantities and in almost all applications.

    To begin with, we will consider working with images, since very often this is one of the causes of sticking.

    The standard component for displaying Image is good, it even supports caching, but it is of little use when used in real projects. When we ran into the limitations of Image a year ago, we had to create our own simple cache of images with automatic scaling - a smaller version was transferred to the cell to display, since with large images the lists simply died (this is not a problem of Xamarin.Forms, but generally any application development, but on Xamarin.Forms she was very sharp).

    Then we tried several different libraries and eventually settled on an excellent component called FFImageLoading .



    It is available in Nuget () and allows you to solve several problems at once:


    • Background image loading with the ability to repeat requests;
    • using placeholder at boot time;
    • automatic scaling of images to control sizes, including removing the Alpha channel on Android for even greater performance;
    • the ability to apply transformations to images after loading (crop to a circle or other shape, apply blur or other special effect);
    • fade-animation of the appearance of the image after loading.

    This is how to use the component when developing on XAML:




    This is how you can further improve the performance of FFImageLoading (class AppDelegate.cs for iOS and MainActivity.cs for Android):



    var config = new Configuration
                {
                    HttpClient = new HttpClient(new ModernHttpClient.NativeMessageHandler()),  //используем быстрые библиотеки для загрузки
                    FadeAnimationDuration = 250,  //ускоряем анимацию появления
                };
    FFImageLoading.ImageService.Instance.Initialize(config);
    

    Working with lists in Xamarin.Forms


    Using FFImageLoading, we have optimized the display of images in lists and now we can move on to the next step.

    The first recommendation is about the ListView working mechanisms. In early versions of Xamarin.Forms, the mechanism for reusing created cells was not supported, which led to the creation of ViewCell instances each time they needed to be displayed - this was the first serious reason for sticking when scrolling.

    The latest versions of Xamarin.Forms have a reuse mechanism for created cells, and to activate it, you need to set the CachingStrategy property to ListViewCachingStrategy.RecycleElement.

    XAML implementation:


    
    	...
    

    C # implementation:


    var listView = new ListView(ListViewCachingStrategy.RecycleElement);
    


    After that, the created instances of ViewCell begin to be reused and the necessary data models are simply connected to them (via Binding) as they are displayed.



    Another interesting way my colleague Kirill suggested - just stop downloading and displaying pictures while scrolling through the list. The creators of FFImageLoading also recommend this method.

    To do this, you need to make your own ListView renderer for each platform and override scroll events.

    Example for Android:


    _listView.ScrollStateChanged += (object sender, ScrollStateChangedEventArgs scrollArgs) => {
      switch (scrollArgs.ScrollState)
      {
      case ScrollState.Fling:
          ImageService.Instance.SetPauseWork(true); // ставим загрузку картинок на паузу 
          break; 
          case ScrollState.Idle: 
          ImageService.Instance.SetPauseWork(false); // возобновляем загрузку картинок 
         // здесь должен быть ваш код отображения изображений в отображаемых ячейках 
          ShowMyImage();      
          break;

    } };


    If necessary, you can also create your own ViewCell implementations through the Custom Renderer mechanism for each platform - this approach may be relevant for complex cells with a lot of built-in controls.



    Also, good results when working with large amounts of data and complex cells can be achieved using the native components UICollectionView (for iOS ) and RecyclerView (for Android ), but this solution can be recommended to advanced developers.

    An example of the use of these classes is presented in the TwinTechs library - it is imperative to get acquainted, as there are videos with optimization results.

    So, at the beginning of the development of Xamarin.Forms, you need to pay special attention to working with lists and approaches to improving productivity . This will allow not to be distracted by these features in the subsequent development.



    Conclusion


    In our article today, we examined the basic mechanisms for optimizing the working environment and the first steps to developing business applications based on Xamarin.Forms.

    In the next article, we will talk about using icon fonts in the Font Awesome style, the Fody tool for shortening code in ViewModel, and the mechanisms for manually rendering our interface elements using the NControlView library.

    Stay connected and add your comments and questions!

    About Authors



    Vyacheslav Chernikov - Head of Development, Binwell . In the past, one of Nokia Champion and Qt Certified Specialist, currently a specialist in Xamarin and Azure platforms. He came into the mobile sphere in 2005, since 2008 he has been developing mobile applications: he started with Symbian, Maemo, Meego, Windows Mobile, then switched to iOS, Android and Windows Phone.

    Other articles of the author:


    useful links


    Read Next