Wednesday 16 May 2018

How to display items in Card View Xamarin Forms

Hi All, I hope you are doing good.

In this post I am gonna be explaining about how to display items in Card View using Xamarin Forms.

Actually CardView was introduced in Android 5.0 (Lollipop). But here we are creating CardView for both the android and iOS platforms using the “Frame” Layout available Xamarin Forms.

In this post I will take one scenario, that is regarding eligibility for Vote.
  • If the person is 18 year or less than 18 then user is not eligible for Vote so we will label the user with Red color in the card.
  • If the person is above 18 then he/she is eligible for Vote so we will label the user with Green color in the card.

Prerequisites:
  • Visual Studio for Windows or Mac
  • Java SDK, Android SDK and Android NDK are for running application in Android.
  • If you want to run application iOS simulator, then Mac machine is mandatory.
  • Need to have an idea about MVVM.

Step 1: Create Xamarin Forms project in Visual studio, in my case I have created project named “XFormsCardView”. After creating the project, the solution structure is as below.


Step 2: Create “ContentView” with the name "CardViewTemplate” under Xamarin Forms PCL. We use this as a item template in the listview so every item of listview renders based this Contentview. Place the following code inside your content view.
    <ContentView.Content>
        <Frame IsClippedToBounds="True"
               HasShadow="True"
               Padding="0"
               BackgroundColor="White" >
            <Frame.OutlineColor>
                <OnPlatform x:TypeArguments="Color"
                        Android="Gray"
                        iOS="Gray"/>
            </Frame.OutlineColor>
            <Frame.Margin>
                <OnPlatform x:TypeArguments="Thickness"
                         Android="10"
                         iOS="10"/>
            </Frame.Margin>
            <StackLayout Orientation="Horizontal">
                <BoxView Color="{Binding HasVote}" WidthRequest="6"/>
                <Grid VerticalOptions="CenterAndExpand"
                     Padding="0"
                     HorizontalOptions="FillAndExpand"
                     BackgroundColor="Transparent">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                    <Label FontAttributes="Bold"
                       Grid.Row="0"
                       HorizontalTextAlignment="Start"
                       VerticalTextAlignment="Center"
                       FontSize="16"
                       Text="{Binding Name, Mode = TwoWay}">
                        <Label.LineBreakMode>
                            <OnPlatform x:TypeArguments="LineBreakMode"
                              Android="NoWrap"
                              iOS="TailTruncation"/>
                        </Label.LineBreakMode>
                    </Label>
                    <BoxView Grid.Row="1" Color="Gray"
                        HorizontalOptions="FillAndExpand"
                        HeightRequest="1"/>
                    <Grid Grid.Row="2"
                       BackgroundColor="Transparent"
                       Padding="4">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>
                        <Label Grid.Row="0"
                              Grid.Column="0"
                              Text="User Age"/>
                        <Label Grid.Row="0"
                              Grid.Column="1"
                              Text="{Binding Age, Mode = TwoWay}"/>
                    </Grid>
                </Grid>
            </StackLayout>
        </Frame>
    </ContentView.Content>

Step 3: Create a Content page with the name “MainPage” under Xamarin Forms PCL. Place following code inside of Content Page.
<StackLayout Orientation="Vertical">
        <Label Text="CardView Demo in Xamarin Forms"
               FontAttributes="Bold"
               FontSize="Medium"
               VerticalOptions="Start"
               HorizontalTextAlignment="Center"
               VerticalTextAlignment="Center"
               BackgroundColor="Transparent"
               HorizontalOptions="CenterAndExpand" />
        <ListView x:Name="listView"
                  SelectedItem="{Binding SelcetedItem,Mode=TwoWay}"
                  HasUnevenRows="True"
                  ItemsSource="{Binding lstUsers}" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <local:CardViewTemplate/>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
If you observe above code, I have added above created “CardViewTemplate” as a viewcell for the listview. If you want use that inside of Content Page, you have to add following line Content Page Tage.
xmlns:local="clr-namespace:XFormsCardView"   
In above line, XFormsCardView is my namespace name of “CardViewTemplate”, so please change it to appropriate namespace based on your project.

Step 4: Create a class with the name “User” with some properties in Xamarin Forms PCL like below
public class User
    {
        public string Name { get; set; }
        public int Age { get; set; }

        // I assume if color is
        // Green, then user has vote
        // Red, then user is below 18
        public Color HasVote { get; set; }
    }

Step 5: Create a class with the name “UserViewModel” with the following in Xamarin Forms PCL
public class UserViewModel
    {
        public IList<User> lstUsers { get; set; }

        public object SelectedItem { get; set; }

        public UserViewModel()
        {
            lstUsers = new List<User>();
            GenerateCardModel();
        }

        private void GenerateCardModel()
        {
            string[] arrNames = {
                "David", "John", "Paul", "Mark", "James",
                "Andrew", "Scott", "Steven", "Robert", "Stephen",
                "William", "Craig", "Michael", "Stuart", "Christopher",
                "Alan", "Colin", "Brian", "Kevin"
            };

            Random rnd = new Random();

            for (var i = 0; i < arrNames.Length; i++)
            {
                var age = rnd.Next(10, 30);
                var user = new User()
                {
                    Name = arrNames[i],
                    Age = age,
                    HasVote = age % 2 == 0 ? Color.Green : Color.Red,
                };
                lstUsers.Add(user);
            }
        }
    }

Step 6: Place the following code in code behind of “MainPage”. This is the place where we have to bind ViewModel  with BindingContext.
public partial class MainPage : ContentPage
       {
              public MainPage()
              {
           
                     InitializeComponent();
                     this.BindingContext = new UserViewModel();

              }
       }
Step 7: Now, you can run your application by setting required platform as a startup. Here in my case I’m running application in Android and the outcome will be as below.
In the following image, the persons who are having green label they are eligible for Vote other are not eligible.



I hope you enjoyed reading this article. Please reach out me through comment if you have any doubts in this post.

No comments:

Post a Comment

Intoduction to Flutter

Hi All, I hope every one is doing good In this article, we will know about the introduction of Flutter.