Forum Xamarin Xamarin.Android

Dynamically create buttons, and button clicks


I am dynamically creating buttons and button clicks from a WCF service, basically a catalog of items and then clicking through to details page for each item.
Button creation:
Button firstButton = new Button(view.Context);
firstButton.Text = "button 1";
firstButton.Id = getItemId;

firstButton.Click += (sender, e) =>
var productFragment = new ProductDetailFragment_1();
productFragment.itemId = getItemId;
.Replace(Resource.Id.content_frame, productFragment)

Now all works. The problem is that I loop through the above as many times as are items in the XML from the WCF, and all clicks end up going to the last loaded item.

Is there a way I can dynamically create the buttons/clicks and have them be unique per item?


  • CarelMeyerCarelMeyer ZAMember ✭✭

    I am new to this forum, why did the markdown of multiple spaces in front of code not work?

  • nodoidnodoid GBMember, Beta ✭✭✭

    The way I typically do this. myData is going to some data dragged in from WCF and myLayout is a vertical layout. I'll leave the handling of where the button is pressed to the gentle reader

    Context c = somethingOnScreen.Context;
    for(int n = 0; n < myData.Count; ++n)
        Button btn = new Button(c);
        btn.Text = "Button " + buttonNumber.ToString();
        int m = new int();
        m = n;
        btn.Tag = m;
        btn.Clicked += HandleButtonClick;
    private void HandleButtonClick(object s, EventArgs e)
        Button btn = (Button)s;
        int tag = (int)btn.Tag;
        // then do as you want

    I'm not sure if it's the Java bindings or something in .NET that needs you to create a new instance of the int and then add that to the tag to ensure you get a unique tag number, but you have to do it.

  • CarelMeyerCarelMeyer ZAMember ✭✭


    Thanks dude. worked like a charm.

    Would never have thought that creating a new int instance to get unique tag number.

  • nodoidnodoid GBMember, Beta ✭✭✭

    No worries mate :)

Sign In or Register to comment.