Xamarin: More Material Design for Your Android Apps

Android developers have been flocking to Material Design since its introduction with the release of Android Lollipop. With the recent update to the Support v7 AppCompat library it has never been easier to add Material Design to target older Android operating systems. Material Design is much more than just the core theming and styling that […]

The post More Material Design for Your Android Apps appeared first on Xamarin Blog.

Ruben Macias: Android ListViews Reinvented

I learned something new last week that I felt I probably should have learned a long time ago.  As I know from my previous experience in Android development, ListViews only scroll vertically.  In the past, there was no out of the box support for horizontal ListViews in Android.  Developers had to create them manually or use 3rd party […]

Daniel Hindrikes: Xamarin.Forms Android CardView

When Google introduced Material Design for Android they introduced a new view called CardView. Xamarin.Forms doesn’t have support for CardView by default but you can easily create your own view that renderers a CardView on Android. First step is to create a Xamarin.Forms control in your shared project. public class CardContentView : ContentView {   […]

Johan Karlsson: Images in a ListView on iOS

There is an odd behavior in Xamarin Forms regarding images that are loaded from an URL and then placed in an ListView. The problem is that there is an await call when fetching images and that the image is set when that call is returned.

Since Xamarin Forms Listview now reuses cells in iOS (as it should) one small piece was overlooked. The reused cells now displays previously displayed images for a short while until the new image is downloaded.

This behavior is mitigated by a cache, so once an image is loaded it’s set instantly the next time the cell is displayed.

I’ve also filed a bug with a sample project available at https://bugzilla.xamarin.com/show_bug.cgi?id=28628 and the sample project to visualize the issue at here.

There are a number of ways around this.

Suggestion one – half-way around

This solution works, but images are blank and then suddenly pops into place. It’s visually ugly, but better than the original version  of the ImageRenderer. What is does is that it sets the Image to null (the UIImage.Image) when IsLoading changes from False to True. The problem is that is does this even when the image isn’t loading from the internet, but from the cache as well, leaving us with no option to initiate a fade in.
assembly: ExportRenderer (typeof (Image), typeof (CustomImageRenderer))]

namespace ImageListView.iOS.Renderers
{
    public class CustomImageRenderer : ImageRenderer
    {
        public CustomImageRenderer()
        {
        }

        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if ((sender as Image).IsLoading)
            {
                // The image will be reset in base if there is one already in the cache.
                // If it isnt already loaded we dont want to display the previous image
                // This is however called each time a cell comes into view so it can‘t
                // be used for opacity fading or likewise...
                // This should be handled by the code in the ImageRenderer
                Control.Image = null;
            }
           
            base.OnElementPropertyChanged(sender, e);
        }
    }
}

Suggestion two – wrap it

Wrap your image in a custom control and handle all the loading and caching yourself.

Suggestion three – rewrite it

Write your own Image-renderer from scratch to take into account when an image is fetched from the cache or not to enable a nice fade in. This is what I hope will come out of the bug report.

Suggestion four – hijack the cache

The next article is going to be about this. But simply put, we highjack the cache and control the image flow from that way. Stay tuned! 😀

Summary

I would go with suggestion one for now and wait for the outcome of the bug report.
Have a great one!

Johan Karlsson: Navigation from a ListView

The problem to be solved

One drawback with the vanilla ListView that comes with Xamarin.Forms is that once an item is selected it can’t be selected again until you select something else and reselect it. Usually this is fine, unless you use the ListView to navigate away to a new page. When you return you cannot re-navigate to the same page again.

The solution

The solution to this is simple, just hook up to the ItemSelected event for the ListView and set the SelectedItem property to null.

So the short version of you quick-googlers would be the following line of code. (in the View)

  // Reset the selected item to make it selectable again
  duckListView.ItemSelected += (s, e) => {
    duckListView.SelectedItem = null; 

And the navigation should be done in the ViewModel

        public Duck SelectedDuck
        {
            set 
            {
                if (value != null)
                {
                    // IoC omitted, we should really get someone else to 
                    // create these objects for us.
                    var viewModel = new DuckViewModel() { Duck = value };
                    var page = new DuckView(viewModel);
                    _navigation.PushAsync(page);
                }
            }
        }

The more verbose version

You could also navigate directly from this event handler, but you should feel it deep in your heart that that is just wrong. Instead we handle navigation in the ViewModel. I’ve created a sample project to do this. Also, I’m doing this without any additional framework that would handle navigation for you so that’s why I need to provide my ViewModel with a navigation interface.

I’ll present each file to you below or just download the sample solution from here.

The Model

Our model is simple. It’s just a duck with a name… As you might recall, a model could be anything really. In this case it’s a simple class.
    
    public class Duck
    {
        public string Name
        {
            get;
            set;
        }
    }

The ViewModel (s)

We’ve got two ViewModels, but it’s really only the MainViewModel that’s interesting. It initializes it’s own data, which usually should be done async from another source. It doesn’t implement INotifyPropertyChanged either, as is should but for this sample it’s good enough.

What to focus on is the SelectedDuck property that handles the navigation. We only implement a setter for this since we reset the selected item anyhow in the view itself and on top of that navigate away from the page.


    /// <summary>
    /// The sample ViewModel. Should implement INotifyPropertyChanged
    /// </summary>
    public class MainViewModel
    {
        private INavigation _navigation;

        public MainViewModel(INavigation navigation)
        {
            _navigation = navigation;

            Ducks = new List<Duck>()
            {
                new Duck() { Name = George },
                new Duck() { Name = Bob },
                new Duck() { Name = Sarah },
                new Duck() { Name = Clint },
            };
        }

        /// <summary>
        /// A list of ducks
        /// </summary>
        /// <value>The ducks.</value>
        public List<Duck> Ducks
        {
            get;
            set;
        }

        public Duck SelectedDuck
        {
            set 
            {
                if (value != null)
                {
                    // IoC omitted, we should really get someone else to 
                    // create these objects for us.
                    var viewModel = new DuckViewModel() { Duck = value };
                    var page = new DuckView(viewModel);
                    _navigation.PushAsync(page);
                }
            }
        }
    }

The other ViewModel (DuckViewModel) simply references the selected duck on the page we navigate to.

   public class DuckViewModel
    {
        public DuckViewModel()
        {
        }

        public Duck Duck
        {
            get;
            set;
        }
    }

The View

That leaves us with the view that consists of two parts; XAML and the code behind. Usually you don’t want any code expect the ViewModel-binding in the code-behind since it’s very platform coupled, but in this case we need to do an exception. We need to reset the SelectedItem property of the ListView.
    public partial class MainView : ContentPage
    {
        public MainView()
        {
            InitializeComponent();
            BindingContext = new MainViewModel(this.Navigation); // Should be injected

            // Reset the selected item to make it selectable again
            duckListView.ItemSelected += (s, e) => {
                duckListView.SelectedItem = null; 
            };
        }
    }


The XAML parts look like this.
xml version=1.0 encoding=UTF8?>
<ContentPage xmlns=http://xamarin.com/schemas/2014/forms xmlns:x=http://schemas.microsoft.com/winfx/2009/xaml x:Class=ListViewNavigation.MainView>
    <ContentPage.Content>

      <ListView x:Name=duckListView
             IsGroupingEnabled=false
             ItemsSource={Binding Ducks}
             HasUnevenRows=true
             SelectedItem={Binding SelectedDuck}>
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
            <Label Font=Large Text={Binding Name} />
        </ViewCell>
      </DataTemplate>
     </ListView.ItemTemplate>
    </ListView>

    </ContentPage.Content>
</ContentPage>

Summary

There is a lot missing in forms of Ioc and base frameworks for MVVM (like MvvmLight och MvvmCross). Is there an alternative for the extreme mvvm-purists? Yes, you could hook up a GestureRecognizer on each item in the ListView but some platform specific animations will be lost if you do so.

Please give feedback what ever you feel like! And if there’s a better way, I would love for you to enlighten me! 😀