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.

6,288 thoughts to “CollectionView Masonry Style Xamarin Forms (Android)”

  1. Hey! Do you know if they make any plugins to safeguard against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard
    on. Any tips?

  2. Pingback: tadalafil canada
  3. I’ve read a few just right stuff here. Definitely worth bookmarking for revisiting. I wonder how much effort you put to create any such fantastic informative website.

  4. Thank you for some other magnificent post. The place else may just anybody get that type of info in such an ideal
    way of writing? I have a presentation subsequent week, and I’m on the search
    for such info.

  5. You actually make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complex and extremely broad for me. I am looking forward for your next post, I’ll try to get the hang of it!

  6. It’s actually a nice and useful piece of information. I’m satisfied that you shared this useful information with us. Please stay us up to date like this. Thanks for sharing.

  7. I’m gone to inform my little brother, that he should also go to see this weblog on regular basis to take updated from most recent news.

  8. Pingback: viagra amazon
  9. I’m impressed, I must say. Rarely do I encounter a blog that’s both equally educative and entertaining, and let me tell you, you have hit the nail on the head. The problem is something which not enough men and women are speaking intelligently about. I am very happy that I found this during my hunt for something regarding this.

  10. Tremendous things here. I’m very satisfied to see your article. Thank you so much and I’m looking ahead to touch you. Will you please drop me a mail?

  11. Hi everybody, here every person is sharing these know-how, so it’s pleasant to read this weblog, and I used to go to see this weblog every day.

  12. Pingback: 36 hour cialis
  13. This is a very good tip especially to those fresh to the blogosphere. Brief but very accurate info… Appreciate your sharing this one. A must read article!

  14. I believe this is one of the most vital information for me. And i am glad reading your article. But should commentary on few normal issues, The website style is wonderful, the articles is in point of fact great : D. Just right task, cheers

  15. After checking out a few of the blog posts on your website, I really appreciate your way of writing a blog. I added it to my bookmark website list and will be checking back soon. Take a look at my web site as well and tell me how you feel.

  16. Wow that was odd. I just wrote an really long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say excellent blog!

  17. I was recommended this website via my cousin. I’m now not positive whether this publish is written via him as no one else realize such precise about my trouble. You are wonderful! Thank you!

  18. I don’t know if it’s just me or if everyone else experiencing problems with your website. It appears as though some of the text within your posts are running off the screen. Can someone else please comment and let me know if this is happening to them too? This may be a issue with my web browser because I’ve had this happen before. Kudos

  19. It’s in fact very complex in this active life to listen news on Television, thus I simply use world wide web for that reason, and get the newest information.

  20. Thanks for some other magnificent article. The place else may just anybody get that type of information in such a perfect manner of writing? I’ve a presentation subsequent week, and I am on the search for such info.

  21. Pingback: cialis daily
  22. Hmm it appears like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog. I too am an aspiring blog writer but I’m still new to everything. Do you have any recommendations for novice blog writers? I’d certainly appreciate it.

  23. Pingback: cytotmeds.com
  24. Howdy just wanted to give you a quick heads up. The words in your article seem to be running off the screen in Opera. I’m not sure if this is a formatting issue or something to do with internet browser compatibility but I figured I’d post to let you know. The design and style look great though! Hope you get the issue fixed soon. Kudos

  25. Hello there! I could have sworn I’ve been to this blog before but after reading through some of the post I realized it’s new to me. Anyways, I’m definitely delighted I found it and I’ll be bookmarking and checking back frequently!

  26. I was pretty pleased to discover this great site. I want to to thank you for ones time due to this fantastic read!!
    I definitely liked every part of it and I have you bookmarked to look
    at new things on your blog.

  27. Hey! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly? My web site looks weird when browsing from my iphone. I’m trying to find a template or plugin that might be able to fix this problem. If you have any recommendations, please share. Cheers!

  28. This is a really good tip especially to those new to the blogosphere. Simple but very accurate information… Thank you for sharing this one. A must read article!

  29. I’ve been exploring for a little for any high quality articles or weblog posts in this sort of area . Exploring in Yahoo I finally stumbled upon this site. Reading this information So i’m glad to convey that I have a very good uncanny feeling I came upon exactly what I needed. I such a lot without a doubt will make sure to do not fail to remember this website and give it a look on a constant basis.

  30. Thanks for one’s marvelous posting! I really enjoyed reading it, you could be a great author. I will make certain to bookmark your blog and may come back someday. I want to encourage continue your great job, have a nice day!

  31. Excellent beat ! I would like to apprentice while you amend your website, how could i subscribe for a blog web site? The account aided me a acceptable deal. I had been tiny bit acquainted of this your broadcast provided bright clear idea

  32. Excellent blog you have here.. It’s hard to find high quality writing like yours these days. I honestly appreciate individuals like you! Take care!!

  33. Greetings I am so thrilled I found your blog page, I really found you by error, while I was looking on Google for something else, Anyways I am here now and would just like to say cheers for a incredible post and a all round enjoyable blog (I also love the theme/design), I don’t have time to browse it all at the minute but I have saved it and also added in your RSS feeds, so when I have time I will be back to read more, Please do keep up the excellent jo.

  34. Hi! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results. If you know of any please share. Thank you!

  35. I am curious to find out what blog platform you’re utilizing? I’m having some small security issues with my latest website and I would like to find something more safe. Do you have any recommendations?

  36. [url=http://ivermectinstrm.com/]ivermectin 3[/url] [url=http://diflucantab.com/]diflucan cost in india[/url] [url=http://buyivermectintablets.com/]ivermectin malaria[/url] [url=http://seroquelx.com/]seroquel xr generic[/url] [url=http://pccialis.com/]buying cialis in nz[/url]

  37. Thanks for the auspicious writeup. It actually used to be a entertainment account it. Glance complex to far introduced agreeable from you! However, how could we keep up a correspondence?

  38. I manage a vape store directory site and we have had a posting from a vape store in the USA that additionally advertises CBD product lines. A Calendar month later on, PayPal has contacted use to say that our account has been limited and have requested us to take out PayPal as a payment method from our vape shop directory site. We do not retail CBD products such as CBD oil. We simply offer internet marketing solutions to CBD companies. I have had a look at Holland & Barrett– the UK’s Reputable Health and wellness Merchant and if you take a good look, you will see that they offer for sale a fairly wide-ranging series of CBD items, primarily CBD oil and they also happen to accept PayPal as a settlement solution. It appears that PayPal is employing double standards to many different companies. Due to this restriction, I can no longer accept PayPal on my CBD-related online site. This has constricted my payment options and now, I am greatly reliant on Cryptocurrency payments and direct bank transfers. I have sought advice from a barrister from a Magic Circle law practice in London and they said that what PayPal is doing is completely illegal and inequitable as it ought to be applying a consistent benchmark to all firms. I am yet to talk with one more lawyer from a US law office in The city of london to see what PayPal’s legal position is in the USA. In the meantime, I would be very appreciative if anybody here at targetdomain could offer me with alternative payment processors/merchants that deal with CBD firms.

  39. Fantastic goods from you, man. I have bear in mind your stuff prior to and you’re just extremely great. I actually like what you’ve received right here, certainly like what you’re saying and the way in which wherein you say it. You’re making it entertaining and you continue to care for to keep it wise. I cant wait to read far more from you. This is actually a tremendous website.

  40. When some one searches for his necessary thing, thus he/she needs to be available that in detail, thus that thing is maintained over here.

  41. Its like you read my thoughts! You seem to understand a lot approximately this, such as you wrote the guide in it or something. I think that you just could do with some percent to force the message house a little bit, however other than that, this is wonderful blog. An excellent read. I’ll certainly be back.

  42. Fantastic beat ! I would like to apprentice while you amend your web site, how could i subscribe for a blog web site? The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast offered bright clear idea

  43. Just want to say your article is as astonishing. The clarity in your post is simply cool and i could assume you are an expert on this subject. Well with your permission allow me to grab your feed to keep updated with forthcoming post. Thanks a million and please keep up the rewarding work.

  44. My spouse and i felt so cheerful that Raymond could conclude his reports from
    the ideas he acquired out of your web site. It’s
    not at all simplistic to just always be making a gift of tactics
    that many other people have been selling. Therefore we understand we now
    have the website owner to appreciate for that. Those illustrations you made, the simple web site navigation, the friendships you will make
    it possible to promote – it’s got all remarkable, and it’s really aiding our son in addition to the family reason why this situation is satisfying,
    which is tremendously indispensable. Thank you for all!

    Stop by my website :: http://www.1stanapa.ru

  45. It’s perfect time to make a few plans for the long run and it is time to
    be happy. I have learn this publish and if I may just I desire to counsel you some attention-grabbing issues or suggestions.

    Perhaps you could write next articles regarding this article.

    I desire to read even more issues about it!

  46. Hey! Someone in my Facebook group shared this website with us so I came to take a look.

    I’m definitely loving the information. I’m
    book-marking and will be tweeting this to my followers!
    Exceptional blog and wonderful style and design.

  47. Woah! I’m really enjoying the template/theme
    of this website. It’s simple, yet effective. A lot of times it’s tough to get that “perfect balance” between usability and appearance.
    I must say you have done a amazing job with this.
    In addition, the blog loads very quick for me on Firefox.

    Excellent Blog!

  48. Hi there! I know this is somewhat off topic but I was wondering which blog platform are you using for this site? I’m getting sick and tired of WordPress because I’ve had issues with hackers and I’m looking at options for another platform. I would be great if you could point me in the direction of a good platform.

  49. I’ve been surfing online greater than three hours lately, but I by no means
    found any fascinating article like yours. It is pretty worth sufficient for me.
    In my opinion, if all webmasters and bloggers made good content as you probably did, the web might be much more helpful than ever before.

  50. Hello there! This post could not be written much better!
    Looking through this article reminds me of my previous
    roommate! He continually kept preaching about this. I
    am going to send this post to him. Fairly certain he’ll have
    a good read. Thanks for sharing!

  51. Excellent goods from you, man. I have be mindful your stuff prior to and you’re simply extremely wonderful. I really like what you’ve obtained right here, really like what you’re stating and the way in which by which you assert it. You are making it entertaining and you continue to care for to stay it sensible. I can not wait to learn far more from you. This is actually a wonderful site.

  52. I just couldn’t leave your website before suggesting that I extremely loved the usual info a person supply in your visitors? Is going to be back steadily to check out new posts

  53. I have been surfing on-line more than 3 hours these days, yet I never found any interesting article like yours. It抯 lovely value enough for me. In my opinion, if all web owners and bloggers made excellent content as you did, the web will probably be a lot more useful than ever before.

  54. Pingback: zithromax 500
  55. https://instantjobinterviewtools.com Vehicle increment allows the user to create a unique number to be produced whenever a brand-new record is put
    in the table. AUTOMOBILE INCREMENT is the key words
    for Oracle, AUTO_INCREMENT in MySQL and IDENTITY key phrase
    can be utilized in SQL WEB SERVER for auto-incrementing.
    Mostly this key words is used to create the primary key for the table.
    Normalization organizes the existing tables and its areas within the database,
    causing minimum replication. It is utilized
    to simplify a table as long as possible while maintaining the special fields.

    If you have actually little to say for yourself, the job interviewer power think you have
    null to state. pl sql interview inquiries I make myself feel magnificent
    ahead the meeting starts. With this inquiry, the recruiter will judge you on exactly
    how you prioritise your task checklist. I expect operations
    with damien once again in the future tense. You mightiness
    require a compounding of different sorts of questions in order to fully cover
    the concern, and also this may diverge betwixt participants.
    Candidates show up to interviews with a coating of thrilling you.

    A primary key is a special kind of unique trick. A
    international key is used to preserve the referential link stability between 2 data
    tables. It stops activities that can ruin web links in between a child and also a moms and dad table.
    A main key is used to specify a column that distinctively
    recognizes each row. Null worth as well as duplicate values are not allowed to be entered in the primary
    vital column. Nevertheless, you may not be given this tip, so it
    is on you to bear in mind that in such a situation a subquery is specifically
    what you require. After you experience the fundamental SQL meeting inquiries, you are
    likely to be asked something a lot more certain.

  56. Link exchange is nothing else however it is only placing the other person’s web site link on your page at proper place and other person will also do same for you.

  57. I don’t know whether it’s just me or if perhaps everyone else experiencing problems with your website. It appears as if some of the written text in your content are running off the screen. Can somebody else please provide feedback and let me know if this is happening to them too? This could be a issue with my internet browser because I’ve had this happen before. Thanks

  58. Excellent post. I was checking constantly this blog and I am impressed! Very useful information specially the last part 🙂 I care for such information much. I was looking for this particular info for a long time. Thank you and best of luck.

  59. Hi there! This is my 1st comment here so I just wanted to give a quick shout out and say I truly enjoy reading through your posts. Can you suggest any other blogs/websites/forums that cover the same subjects? Thank you so much!

  60. I would like to thank you for the efforts you’ve put in writing this blog. I’m hoping to check out the same high-grade blog posts from you later on as well. In truth, your creative writing abilities has encouraged me to get my own website now 😉

  61. Great post. I was checking constantly this blog and I’m impressed! Extremely useful info specifically the last part 🙂 I care for such info a lot. I was looking for this particular information for a long time. Thank you and good luck.

  62. I’ll immediately grab your rss as I can’t in finding your e-mail subscription hyperlink or e-newsletter service. Do you have any? Kindly permit me understand so that I may just subscribe. Thanks.

  63. This is really interesting, You’re a very skilled blogger. I have joined your rss feed and look forward to seeking more of your magnificent post. Also, I’ve shared your site in my social networks!

  64. It’s really a cool and helpful piece of info. I’m glad that you simply shared this helpful info with us. Please stay us up to date like this. Thanks for sharing.

  65. Hmm is anyone else encountering problems with the images on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog. Any feed-back would be greatly appreciated.

  66. I don’t know whether it’s just me or if perhaps everyone else experiencing issues with your site. It looks like some of the written text in your posts are running off the screen. Can someone else please provide feedback and let me know if this is happening to them too? This could be a problem with my web browser because I’ve had this happen previously. Thank you

  67. An intriguing discussion is worth comment. I do believe that you need to publish more about this subject, it may not be a taboo matter but usually people don’t discuss such issues. To the next! All the best!!

  68. It’s really a great and useful piece of information. I’m happy that you simply shared this useful information with us. Please stay us up to date like this. Thank you for sharing.

  69. After I originally commented I appear to have clicked the -Notify me when new comments are added- checkbox and now every time a comment is added I receive four emails with the exact same comment. Perhaps there is an easy method you are able to remove me from that service? Cheers!

  70. I am really enjoying the theme/design of your web site. Do you ever run into any web browser compatibility issues?
    A handful of my blog visitors have complained about my site not working correctly in Explorer but looks great in Firefox.
    Do you have any solutions to help fix this problem?

  71. I’m not sure exactly why but this blog is loading very slow for me. Is anyone else having this problem or is it a issue on my end? I’ll check back later on and see if the problem still exists.

  72. I do consider all the ideas you have introduced in your post. They are really convincing and will certainly work. Nonetheless, the posts are too quick for novices. May just you please prolong them a bit from next time? Thanks for the post.

  73. I’m curious to find out what blog platform you’re utilizing? I’m experiencing some small security problems with my latest site and I’d like to find something more secure. Do you have any solutions?

  74. Kaan Yıldırım’la olan ilişkisinin kendisini yorduğunu ve Mehmet Dinçerler’e ilk görüşte aşık olduğunu
    belirten Hadise, ‘Kaan beni çok yordu. Savaştan çıkmış gibiydim.
    Daha önce bitirmek istedim, ‘toparlayalım’ diye yalvardı.
    Her şeyime karışıyordu; işime, fotoğraflarıma.
    ‘Ailem ilişkinin basında çıkmasını istemiyor.’ diyordu.
    Mesaj atıp bitirdim. Kendisine tahammülüm kalmadığını belirttim.
    Mehmet ise ilk bakışta aşk oldu” dedi.
    yeni sevgilisi

  75. Hi there, just became aware of your blog through Google, and found that it’s really informative. I’m gonna watch out for brussels. I will be grateful if you continue this in future. Many people will be benefited from your writing. Cheers!

  76. I am really inspired with your writing talents and also with the structure
    for your blog. Is this a paid subject matter or did you customize it your self?
    Either way stay up the excellent high quality writing, it is rare to look a nice weblog like this one today..

  77. This is really interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your excellent post. Also, I’ve shared your web site in my social networks!

  78. Do you mind if I quote a few of your posts as long as I provide credit and sources back to your blog? My blog is in the very same niche as yours and my users would truly benefit from a lot of the information you provide here. Please let me know if this okay with you. Thanks!