我刚刚开始学习Xamarin Android。我有几个带有相同点击事件处理程序的按钮。
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&#34; FlipperBtn_Click&#34;方法我想知道按下哪个按钮并从此按钮获取值。我希望通过将div分配给我想要的多个属性来实现HTML5中的某些功能。我在考虑android&#34; Tag&#34;属性,并试图做这样的事情:
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);
}
芽我不明白很少有人想:
a)使用&#34; key&#34;的目的是什么?在SetTag方法?
b)如何将c#类对象转换为Java.Lang.Object?
答案 0 :(得分:6)
您无需在按钮中设置标签即可找到被点击的女巫。
这样做:
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;
}
}
在Xamarin Android中,您有两种设置标记的方法。 通过property或method。
button.SetTag(1, "value");
或者:
button.Tag = "value";