Shagohad Shagohad - 5 months ago 34
Android Question

Is there possibility to assign a value to Android Button in Xamarin?

I've just started learning about Xamarin Android. I've got few buttons with the same click event handler.

private Button flipper1Btn;
private Button flipper2Btn;
private ViewFlipper flipper;
private TextView text;

protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);

setControls();
setEvents();
}

private void setControls()
{
flipper = FindViewById<ViewFlipper>(Resource.Id.viewFlipper1);
flipper1Btn = FindViewById<Button>(Resource.Id.button1);
flipper2Btn = FindViewById<Button>(Resource.Id.button2);
text = FindViewById<TextView>(Resource.Id.textView1);

}
private void setEvents()
{
flipper1Btn.Click += FlipperBtn_Click;
flipper2Btn.Click += FlipperBtn_Click;
}

#region Events

private void FlipperBtn_Click(object sender, EventArgs e)
{
Button sendBtn = (Button)sender;
}

#endregion


In "FlipperBtn_Click" method I would like to recognize which button was pressed and get value from this button. I would like to achieve something like in HTML5 by assign to div as many attribute I want. I was thinking about android "Tag" propertie, and trying to do something like this:

private void setControls()
{
flipper = FindViewById<ViewFlipper>(Resource.Id.viewFlipper1);
flipper1Btn = FindViewById<Button>(Resource.Id.button1);
flipper2Btn = FindViewById<Button>(Resource.Id.button2);
text = FindViewById<TextView>(Resource.Id.textView1);
FlipperBtnTag tag1 = new FlipperBtnTag("tag1", "tag1Value");
FlipperBtnTag tag2 = new FlipperBtnTag("tag2", "tag2Value");

flipper1Btn.SetTag(1, tag1);
flipper1Btn.SetTag(2, tag2);
}


Bud I don't understand few thinks:
a) What is a purpose of using "key" in SetTag method?
b) How Can I convert c# class object into Java.Lang.Object?

Answer

You don't need to set tags in the buttons to find witch is being clicked.

Do this:

flipper1Btn = FindViewById<Button>(Resource.Id.button1);
flipper2Btn = FindViewById<Button>(Resource.Id.button2);

flipper1Btn += Button_Click;
flipper2Btn += Button_Click;

void Button_Click(object sender, System.EventArgs e)
{
    var button = (Button)sender;

    switch (button.Id)
    {
        case Resource.Id.button1:
            // Do Stuff here
        break;

        case Resource.Id.button2:
            // Do Stuff here
        break;

        default:
        break;
    }
}

In Xamarin Android you have two ways to set tags. Via property or via method.

button.SetTag(1, "value");

Or:

button.Tag = "value";