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

Advertisement

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

Xamarin Forms: Menampilkan data pada ListView (Part 3)

Pada blog sebelumnya saya telah membahas bagaimana cara untuk menampilkan data pada kontrol ListView dengan sumber data berupa koleksi objek. Pada tutorial kali ini saya akan membahas bagaimana cara menampilkan gambar pada kontrol ListView.

Pada contoh yang sebelumnya anda sudah menggunakan ListView ItemTemplate untuk menampilkan informasi berupa Text dan Detail. Kontrol ListView pada Xamarin juga menyediakan template yang menampilkan tidak hanya data berupa text, pada contoh dibawah ini kita akan mencoba untuk menampilkan data berupa gambar pada kontrol ListView.

1. Pada project portable, tambahkan halaman xaml baru dengan nama ListViewImageCell.xaml.

2. Kemudian tambahkan kode 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.ListViewImageCell">
  <ListView x:Name="listView" ItemsSource="{Binding ListItems}">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ImageCell ImageSource="{Binding Source}" Text="{Binding Title}" Detail="{Binding Description}" />
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</ContentPage>

3. Pada kode xaml diatas dapat dilihat bahwa elemen Data Template yang digunakan berbeda dengan contoh sebelumnya yang menggunakan element TextCell, pada kasus ini digunakan element ImageCell untuk menampilkan data berupa image dan text.

4. Pada folder Models modifikasi class ListItem.cs yang sebelumnya sudah dibuat. Tambahkan property Source yang akan digunakan untuk menyimpan informasi gambar.

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

5. Pada file ListViewImageCell.xaml.cs tambahkan kode berikut ini

    public partial class ListViewImageCell : ContentPage
    {
        public ListViewImageCell()
        {
            InitializeComponent();
            BindingContext = new ListViewImageCellViewModel();
        }


        public class ListViewImageCellViewModel : BindableObject
        {
            private List<ListItem> listItems;
            public List<ListItem> ListItems
            {
                get { return listItems; }
                set
                {
                    listItems = value;
                    OnPropertyChanged("ListItems");
                }
            }

            public ListViewImageCellViewModel()
            {
                listItems = new List<ListItem>
                {
                    new ListItem { Source="first.png", Title="Mystic", Description="Mystic team blue badge" },
                    new ListItem { Source="second.png", Title="Instinct",Description="Instinct team yellow badge" },
                    new ListItem { Source="third.png", Title="Valor",Description="Valor team red badge" }
                };
            }
        }
    }

6. Tambahkan juga class dengan nama ListViewImageCellViewModel.cs. Class ini berisi objek-objek yang akan ditampilkan pada kontrol ListView.

7. Kode diatas mirip dengan contoh sebelumnya, hanya ada tambahan inisialisasi satu property baru yaitu Source yang berisi nama file image yang akan ditampilkan.

8. Untuk menambahkan image yang akan ditampilkan, tambahkan image yang akan ditampilkan kedalam project Droid (untuk aplikasi android) di folder Resources\drawable. Pada contoh berikut ditambahkan tiga file bertipe .png kedalam folder tersebut. Anda dapat download asset tersebut disini

image

9. Kemudian tekan tombol F5 untuk menjalankan program pada emulator, hasil dari aplikasi yang sudah dibuat dapat dilihat pada kode berikut ini. Jangan lupa untuk mengganti inisalisasi page yang diload oleh aplikasi pada App.xaml.cs

image