CollectionView Masonry Style Xamarin Forms (Android)

En mas de una ocasión hemos visto este estilo para algunos Menu, en aplicaciones (tipo Pinterest) o el Menu de Opciones de Facebook, este caso vamos a crear este mismo estilo para una aplicación en Xamarin Form para nuestro Android Project.

Vamos a crear nuestro proyecto (Actualmente estoy utilizando la extensión de Prism para general el proyecto)

Lo primero que debemos hacer es crear un Custom Render para nuestro Collection View.

Vamos a crear una carpeta con el nombre Controls y dentro de, crearemos una clase que se llame CollectionViewMasonry.cs y hacemos que herede del CollectionView de Xamarin.Forms, de tal manera que quede así.

public class CollectionViewMasonry : CollectionView
{

}

Ahora vamos a crear una carpeta dentro de nuestro proyecto Android con el nombre CustomControls y dentro de, vamos a crear una clase llama CustomCollectionView.cs y la pondremos a heredar de CollectionViewRenderer proveniente de Xamarin.Forms.Platform.Android y dentro de la clase vamos a escribir el siguiente código.

[assembly: ExportRenderer(typeof(CollectionViewMasonry), typeof(CustomCollectionView))]
namespace MasonryStyle.Droid.CustomControls
{
    public class CustomCollectionView : CollectionViewRenderer
    {
        public CustomCollectionView(Context context):base(context)
        {

        }

        protected override void OnElementChanged(ElementChangedEventArgs<ItemsView> elementChangedEvent)
        {
            base.OnElementChanged(elementChangedEvent);

            if (elementChangedEvent.NewElement != null)
            {
                StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.Vertical);
                SetLayoutManager(manager);
            }
        }

    }
}

Luego de esto, vamos a volver a nuestro proyecto compartido crearemos una carpeta llamada Models y agregaremos la siguiente clase MenuItems.cs y agregaremos la siguientes propiedades.

public class MenuItems
{
   public int Id { get; set; }
   public string BackgroundColor { get; set; }
   public int Height { get; set; }
}

Vamos ahora dentro de nuestra carpeta de ViewModels y abrimos el archivo MainPageViewModel.cs y vamos a agregar el código que llenara nuestra lista, quedando de la siguiente manera.

public class MainPageViewModel : ViewModelBase
    {

        public ObservableCollection<MenuItems> MenuItemsList { get; set; } = new ObservableCollection<MenuItems>();
        public ICommand LoadData { get; set; }

        public MainPageViewModel(INavigationService navigationService)
            : base(navigationService)
        {
            Title = "Main Page";

            LoadData = new DelegateCommand(() => LoadDataMenuItems());
            LoadData.Execute(null);
        }

        public void LoadDataMenuItems()
        {
            var rnd = new Random();
            string[]  ColorsArray = { "#FF7D7D", "#FFF3B8", "#A1CAFF", "#FDBAFF", "#ACB7FF", "#B2FFC7", "#BEBEBE", "#FEC1C1", "#DBB6D5", "#FFC1AA" };
            for (var i = 1; i <= 30; i++) {
                MenuItemsList.Add(new MenuItems { 
                    Id = i,
                    BackgroundColor = ColorsArray[rnd.Next(0,9)],
                    Height = rnd.Next(86,196)
                });
            }
        }
    }

Ahora vamos a ir a nuestra carpeta Views y abriremos el archivo MainPage.xaml y dentro de las propiedades del ContentPage vamos a agregar el siguiente namespace.

xmlns:Controls="clr-namespace:MasonryStyle.Controls"

y ahora eliminaremos el StackLayout que esta creado por defecto y vamos a agregar el diseño de nuestra vista, quedando el código de la siguiente manera.

<?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="MasonryStyle.Views.MainPage"
             Title="{Binding Title}"
             xmlns:Controls="clr-namespace:MasonryStyle.Controls">

    <ContentPage.Content>
        <StackLayout>
            <Controls:CollectionViewMasonry ItemsSource="{Binding MenuItemsList}" Margin="5">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <StackLayout>
                            <Frame Margin="5" BackgroundColor="{Binding BackgroundColor}" HeightRequest="{Binding Height}">
                                <Label Text="{Binding Id}" HorizontalOptions="Center" VerticalOptions="Center"/>
                            </Frame>
                        </StackLayout>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </Controls:CollectionViewMasonry>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Ahora ejecutaremos nuestra aplicación y tendremos nuestro efecto creado.

Si te gusto este post no te olvides de comentar para que la motivación de seguir creando contenido de ayuda siga en pie, gracias por tu apoyo.

173 thoughts to “CollectionView Masonry Style Xamarin Forms (Android)”

  1. Хотите сыграть в Хотите играть в рулетку? В казино Вулкан есть 3 вида рулетки: Европейская, VIP и без зеро. Многие игроки выбирают рулетку без зеро, ведь благодаря отсутствию сектора зеро шансы на выигрыш увеличиваются

    Тогда переходи сюда :
    смотреть порно в казино

    Где Казино устраивает интересные турниры. Игрокам необходимо пройти простую регистрацию в турнире и заплатить взнос в призовой фонд. Остается только выиграть турнир

  2. Играть в online игровые аппараты которые размещены на самом крутом игорном портале Вулкан 777 в Украине на средства непосредственно тут
    http://www.istitutocomprensivoroccarainola.gov.it/assortiment-avtomatov-s-bonusami-v-populjarnom/.
    Зарегистрируйся, участвую в соревнованиях и получай четкие награды.

  3. great post, very informative. I wonder why the other experts of this sector don’t notice this. You should continue your writing. I’m confident, you’ve a great readers’ base already!

  4. [url=https://cialistadalafilpill.com/]order brand name cialis online[/url] [url=https://cialisprof.com/]buy cialis generic[/url] [url=https://viagradtab.com/]sildenafil 50 mg cost[/url] [url=https://ddrpills.com/]reputable online pharmacy uk[/url] [url=https://366pills.com/]2.5 mg prednisone[/url]

  5. [url=https://viagraxtab.com/]sildenafil generic cheap[/url] [url=https://oppviagra.com/]cheap viagra buy[/url] [url=https://viagraoff.com/]buy sildenafil 20 mg[/url] [url=https://viagraxi.com/]viagra canadian pharmacy generic[/url] [url=https://cialisfour.com/]order cialis 10mg[/url]

  6. [url=http://viagradtab.com/]sildenafil 80 mg[/url] [url=http://cialisipr.com/]online tadalafil canada[/url] [url=http://pnviagra.com/]buy viagra pills online[/url] [url=http://worxpharm.com/]wellbutrin 100mg price[/url] [url=http://toapills.com/]all in one pharmacy[/url] [url=http://pharmacy720.com/]online pharmacy viagra[/url] [url=http://cialisemed.com/]average cost of cialis prescription[/url] [url=http://viagracialissildenafil.com/]cheap viagra without prescription[/url] [url=http://ddrpills.com/]buy amitriptyline 50 mg uk[/url] [url=http://viagraoff.com/]buy female viagra online australia[/url]

  7. Great ?I should certainly pronounce, impressed with your site. I had no trouble navigating through all the tabs as well as related information ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or anything, website theme . a tones way for your customer to communicate. Nice task..

  8. Based on my research, after a property foreclosure home is available at a bidding, it is common with the borrower to still have some sort ofthat remaining balance on the loan. There are many loan companies who attempt to have all costs and liens paid by the subsequent buyer. Nevertheless, depending on selected programs, restrictions, and state guidelines there may be some loans which are not easily sorted out through the exchange of personal loans. Therefore, the obligation still falls on the customer that has received his or her property in foreclosure process. Thanks for sharing your opinions on this blog site.

  9. I抣l immediately take hold of your rss as I can’t in finding your e-mail subscription link or newsletter service. Do you have any? Please let me realize in order that I may just subscribe. Thanks.

  10. One other issue is that if you are in a problem where you would not have a cosigner then you may really need to try to exhaust all of your federal funding options. You will find many grants and other grants that will supply you with funding to aid with university expenses. Thanks alot : ) for the post.

  11. I love your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to construct my own blog and would like to know where u got this from. thank you

  12. One thing is the fact one of the most common incentives for using your cards is a cash-back and also rebate present. Generally, you get 1-5 back on various buying. Depending on the card, you may get 1 again on most acquisitions, and 5 again on expenditures made using convenience stores, gas stations, grocery stores as well as ‘member merchants’.

  13. Helpful info. Fortunate me I discovered your web site by accident, and
    I am stunned why this twist of fate did not happened earlier!
    I bookmarked it. 0mniartist asmr

  14. Hmm it appears like your blog ate my first comment (it was super
    long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly
    enjoying your blog. I too am an aspiring blog writer but I’m still
    new to the whole thing. Do you have any recommendations
    for novice blog writers? I’d genuinely appreciate it.
    asmr 0mniartist

Leave a Reply

Your email address will not be published. Required fields are marked *