Navigasi pada Xamarin Forms

Pada tutorial berikut saya akan menjelaskan konsep navigasi pada Xamarin Forms. Navigasi digunakan untuk memudahkan pengguna berpindah halaman dengan mudah. Fitur untuk navigasi meliputi menu, tap icon, tombol, tabs, dan list items.

Bentuk Navigasi pada Xamarin Forms

Ada beberapa pattern yang sering digunakan pada navigasi diantaranya:

  • Hierarchical
  • Modal
  • Drill-down
  • Navigation drawer
  • Tabs
  • Springboard
  • Carousel

Pada contoh yang pertama akan ditunjukan bagaimana cara untuk menambahkan Navigation Page, teknik ini digunakan untuk memanggil halaman selanjutnya dari halaman pertama.

1. Tambahkan page xaml baru dengan nama NavigationPage1.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage Title="Navigasi Hirarki" xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Bab4.NavigationPage1">
  <ContentPage.Content>
    <StackLayout>
      <Label Text="Home Page" FontSize="40"></Label>
      <Button Text="Go To Second Page" x:Name="btnSecond"></Button>
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

2. Tambahkan kode berikut pada App.xaml.cs

        public App()
        {
            InitializeComponent();

            MainPage = new NavigationPage(new NavigationPage1());
        }

3. Tambahkan kode pada NavigationPage1.xaml.cs. Method Navigation.PushAsync() digunakan untuk memanggil halaman selanjutnya.

    public partial class NavigationPage1 : ContentPage
    {
        public NavigationPage1()
        {
            InitializeComponent();
            btnSecond.Clicked += BtnSecond_Clicked;
        }

        private async void BtnSecond_Clicked(object sender, EventArgs e)
        {
            
            await Navigation.PushAsync(new NavigationPage2());
        }
    }

4. Tambahkan halaman NavigationPage2.xaml.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Bab4.NavigationPage2">
  <ContentPage.Content>
    <StackLayout>
      <Label Text="Second Page" FontSize="40"></Label>
      <Button x:Name="btnBack" Text="Back"/>
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

5. Kemudian tambahkan kode pada NavigationPage2.xaml.cs. Method Navigation.PopAsync() digunakan untuk kembali ke halaman sebelumnya.

    public partial class NavigationPage2 : ContentPage
    {
        public NavigationPage2()
        {
            InitializeComponent();

            
            btnBack.Clicked += async (sender, e) =>
            {
                await Navigation.PopAsync(true);
            };
        }
    }

6. Tampilan dibawah menunjukan bagaimana cara navigasi antar form, dari form Home Page ke form Second Page.

image

image

Advertisement

Xamarin Forms: Menggunakan Context Action pada ListView

Pada artikel kali ini saya akan menjelaskan bagaimana menggunakan Context Action yang ada di dalam kontrol ListView.

Context Action adalah tombol berupa bar yang akan muncul ketika pengguna melakukan left-swiped pada iOS dan long-pressed pada Android.

1. Tambahkan halaman xaml baru dengan nama ListViewContextAction.xaml, kemudian tambahkan kode berikut:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Bab3.ListViewContextAction">
  <ContentPage.Padding>
    <OnPlatform x:TypeArguments="Thickness">
      <OnPlatform.iOS>10,20,10,5</OnPlatform.iOS>
      <OnPlatform.Android>10,5,10,5</OnPlatform.Android>
    </OnPlatform>
  </ContentPage.Padding>
  
  <ListView ItemsSource="{Binding ListItems}" RowHeight="100" BackgroundColor="Black" HasUnevenRows="True">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
          <ViewCell.ContextActions>
            <MenuItem Text="More" Command="{Binding MoreCommand}" />
            <MenuItem Text="Delete" Command="{Binding DeleteCommand}" IsDestructive="True" />
          </ViewCell.ContextActions>
          <StackLayout HorizontalOptions="StartAndExpand" Orientation="Horizontal" Padding="5,10,5,15">
            <StackLayout HorizontalOptions="StartAndExpand" Orientation="Vertical">
              <Label HorizontalOptions="Start" FontSize="20" FontAttributes="Bold" TextColor="White" Text="{Binding Title}"/>
              <Label HorizontalOptions="Start" FontSize="12" FontAttributes="Bold" TextColor="White" Text="{Binding Description}"/>
            </StackLayout>
            <Label HorizontalOptions="End" FontSize="25" TextColor="Aqua" Text="{Binding Price}"/>
          </StackLayout>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</ContentPage>

2. Buat class ListItem yang diturunkan dari BindableObject

        public class ListItem : BindableObject
        {
            public string Source { get; set; }
            public string Title { get; set; }
            public string Description { get; set; }
            public string Price { get; set; }

            private Command moreCommand;

            public Command MoreCommand
            {
                get { return moreCommand; }
                set { moreCommand = value; OnPropertyChanged("MoreCommand"); }
            }

            private Command deleteCommand;
            public Command DeleteCommand
            {
                get { return deleteCommand; }
                set { deleteCommand = value; OnPropertyChanged("DeleteCommand"); }
            }

            public ListItem()
            {
                MoreCommand = new Command(MoreRequested);
                deleteCommand = new Command(DeleteRequested);
            }

            void MoreRequested()
            {
                MessagingCenter.Send<ListItem>(this, "MoreRequested");
            }

            void DeleteRequested()
            {
                MessagingCenter.Send<ListItem>(this, "DeleteRequested");
            }
        }

3. Buat class ViewModel untuk membinding data pada kontrol ListView.

    public class ListViewContextActionViewModel : BindableObject
    {
        readonly Func<string, string, string, Task> displayAlertAction;

        private List<ListItem> listItems;

        public List<ListItem> ListItems
        {
            get { return listItems; }
            set { listItems = value; OnPropertyChanged("ListItems"); }
        }

        public ListViewContextActionViewModel(Func<string, string, string, Task> displayAlertAction)
        {
            this.displayAlertAction = displayAlertAction;
            ListItems = new List<ListItem> {
                new ListItem {Title = "First", Description="1st item", Price="$100.00"},
                new ListItem {Title = "Second", Description="2nd item", Price="$200.00"},
                new ListItem {Title = "Third", Description="3rd item", Price="$300.00"}
            };

            MessagingCenter.Subscribe<ListItem>(this, "MoreRequested", MoreRequested);
            MessagingCenter.Subscribe<ListItem>(this, "DeleteRequested", DeleteRequested);
        }

        void MoreRequested(ListItem listItem)
        {
            displayAlertAction.Invoke("More", listItem.Title + " more was clicked", "OK");
        }

        void DeleteRequested(ListItem listItem)
        {
            displayAlertAction.Invoke("Delete", listItem.Title + " delete was clicked", "OK");
   
        }
}

3. Terakhir tambahkan kode berikut pada file ListViewContextAction.xaml.cs

    public partial class ListViewContextAction : ContentPage
    {
        public ListViewContextAction()
        {
            InitializeComponent();

            BindingContext = new ListViewContextActionViewModel(DisplayAlert);
        }
    }

4. Jalankan program, maka anda dapat melihat hasilnya sebagai berikut:

image

Xamarin Forms: Menambahkan Tombol pada ListView

Pada artikel kali ini saya akan mencontohkan bagaimana cara menambahkan tombol kedalam kontrol ListView. Untuk mem-binding event yang ada pada tombol kita akan menggunakan model arsitektur MVVM (Model View View Model).

Untuk kasus yang lebih komplek, kita juga dapat menambahkan kontrol seperti tombol pada ListView. Kita juga dapat menambahkan event handler yang dapat dipanggil ketika tombol yang dibuat didalam kontrol ListView tersebut diklik.

1. Tambahkan xaml page baru dengan nama ListViewButton.xaml.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Bab3.ListViewButton">
  <ContentPage.Padding>
    <OnPlatform x:TypeArguments="Thickness">
      <OnPlatform.iOS>10,20,10,5</OnPlatform.iOS>
      <OnPlatform.Android>10,5,10,5</OnPlatform.Android>
    </OnPlatform>
  </ContentPage.Padding>
  <StackLayout Orientation="Vertical">
    <ListView ItemsSource="{Binding ListItems}" RowHeight="100" BackgroundColor="Black" HasUnevenRows="True">
      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <StackLayout HorizontalOptions="StartAndExpand" Orientation="Horizontal" Padding="5,10,5,15">
              <StackLayout HorizontalOptions="Start" Orientation="Vertical">
                <Label HorizontalOptions="Start" FontSize="20" FontAttributes="Bold" TextColor="White" Text="{Binding Title}"/>
                <Label HorizontalOptions="Start" FontSize="12" FontAttributes="Bold" TextColor="White" Text="{Binding Description}"/>
              </StackLayout>
              <StackLayout HorizontalOptions="EndAndExpand" Orientation="Horizontal" WidthRequest="260">
                <Label HorizontalOptions="Center" FontSize="25" TextColor="Aqua" Text="{Binding Price}" />
                <Button Text="Buy Now" BackgroundColor="Teal" HorizontalOptions="End" Command="{Binding BuyCommand}"/>
                <Button Text="Sell" BackgroundColor="Purple" TextColor="White" HorizontalOptions="End" Command="{Binding SellCommand}"/>
              </StackLayout>
            </StackLayout>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
  </StackLayout>
</ContentPage>

2. Tambahkan juga kode pada file ListViewButton.xaml.cs. Tambahkan juga class ListItem yang berisi informasi properti yang akan ditampilkan pada list beserta dengan command-nya.

using Xamarin.Forms;

namespace Bab3
{
    public class ListItem : BindableObject
    {
        public string Source { get; set; }
        private string title;

        public string Title
        {
            get { return title; }
            set { title = value;
                OnPropertyChanged("Title");
            }
        }

        public string Description { get; set; }
        public string Price { get; set; }

        private Command buyCommand;

        public Command BuyCommand
        {
            get { return buyCommand; }
            set { buyCommand = value;
                OnPropertyChanged("BuyCommand");
            }
        }

        private Command sellCommand;

        public Command SellCommand
        {
            get { return sellCommand; }
            set { sellCommand = value;
                OnPropertyChanged("SellCommand");
            }
        }


        public ListItem()
        {
            BuyCommand = new Command(BuyRequested);
            SellCommand = new Command(SellRequested);
        }

        void SellRequested()
        {
            MessagingCenter.Send<ListItem>(this, "SellRequested");
        }

        void BuyRequested()
        {
            MessagingCenter.Send<ListItem>(this, "BuyRequested");
        }

    }

    public class ListViewButtonViewModel : BindableObject
    {
        readonly Func<string, string, string, Task> displayAlertAction;

        private List<ListItem> listItems;

        public List<ListItem> ListItems
        {
            get { return listItems; }
            set
            {
                listItems = value;
                OnPropertyChanged("ListItems");
            }
        }



        public ListViewButtonViewModel(Func<string,string,string,Task> displayAlertAction)
        {
            this.displayAlertAction = displayAlertAction;
            ListItems = new List<ListItem> {
                new ListItem {Title = "First", Description="1st item", Price="Rp.100.00"},
                new ListItem {Title = "Second", Description="2nd item", Price="Rp.200.00"},
                new ListItem {Title = "Third", Description="3rd item", Price="Rp.300.00"}
            };

            MessagingCenter.Subscribe<ListItem>(this, "BuyRequested",BuyRequested);
            MessagingCenter.Subscribe<ListItem>(this, "SellRequested", (sender) =>
            {
                var data = (ListItem)sender;
                data.Title = "Item Sold";
            });
            
        }

        

        void BuyRequested(ListItem listItem)
        {
            displayAlertAction.Invoke("Button", listItem.Title + " was clicked", "OK");
        }
    }

    public partial class ListViewButton : ContentPage
    {
        public ListViewButton()
        {
            InitializeComponent();

            BindingContext = new ListViewButtonViewModel(DisplayAlert);

            
        }
    }
}

3. Hasil dari program yang dijalankan pada emulator adalah sebagai berikut:

image

Xamarin Forms: Custom ListView

Pada artikel ini saya akan membahas bagaimana cara membuat custom ListView. Pada contoh sebelumnya, saya sudah menunjukan bagaimana penggunaan elemen ItemTemplate yang sudah disediakan oleh Xamarin Form untuk menampilkan Text dan Image. Pada contoh ini akan ditunjukan cara untuk kustomisasi kontrol ListView.

1. Pada project portable, tambahkan halaman xaml baru dengan nama ListViewCustom.xaml. Kemudian tambahkan xaml berikut ini.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Modul3.ListViewCustom">
  <ListView x:Name="listView" ItemsSource="{Binding ListItems}" RowHeight="80" BackgroundColor="Black">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
          <StackLayout HorizontalOptions="StartAndExpand" Orientation="Horizontal" Padding="25,10,55,15">
            <StackLayout HorizontalOptions="StartAndExpand" Orientation="Vertical">
              <Label HorizontalOptions="Start" FontSize="20" FontAttributes="Bold" TextColor="White" Text="{Binding Title}"/>
              <Label HorizontalOptions="Start" FontSize="12" FontAttributes="Bold" TextColor="White" Text="{Binding Description}"/>
            </StackLayout>
            <Label HorizontalOptions="End" FontSize="25" TextColor="Aqua" Text="{Binding Price}" />
          </StackLayout>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</ContentPage>

2. Pada kode xaml diatas dapat dilihat bahwa kontrol ListView dapat mempunyai ItemTemplate yang berupa ViewCell. Element ViewCell ini sangat fleksible sehingga dapat diisi dengan element lain. Pada contoh diatas dapat dilihat bahwa ViewCell diisi dengan tiga kontrol label yang disusun menggunakan StackLayout.

3. Pada folder Models modifikasi class ListItem yang sebelumnya sudah dibuat dengan menambahkan property baru yaitu Price.

    public class ListItem
    {
        public string Source { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Price { get; set; }
    }

4. Tambahkan kode pada file ListViewCustom.xaml.cs sebagai berikut:

    public partial class ListViewCustom : ContentPage
    {
        public ListViewCustom()
        {
            InitializeComponent();
            BindingContext = new ListViewCustomViewModel();
        }

        public class ListViewCustomViewModel : BindableObject
        {
            private List<ListItem> listItems;

            public List<ListItem> ListItems
            {
                get { return listItems; }
                set
                {
                    listItems = value;
                    OnPropertyChanged("ListItems");
                }
            }

            public ListViewCustomViewModel()
            {
                listItems = new List<ListItem>
                {
                    new ListItem { Title="Pokeball", Description="Pokeball Red", Price="Rp.10.000" },
                    new ListItem {Title="Masterball",Description="Masterball Blue",Price="Rp.20.000" },
                    new ListItem {Title="Ultraball",Description="Ultraball Yellow",Price="Rp.50.000" }
                };
            }
        }

5. Untuk menjalankan program tekan tombol F5, maka anda akan dapat melihat hasilnya pada android emulator. Jangan lupa untuk mengganti inisalisasi page yang diload oleh aplikasi pada App.xaml.cs

image