xamarin android如何监听单击事件

时间:2022-10-26 22:35:51

在xamarin android单击事件是最基础的事情,看过菜鸟上的android教程时,java写的都是监听事件,为一个按钮,单选按钮、多选按钮的单击事件有三种,前面两种用的非常普遍,也很简易,我这里主要就是写一下xamarin android中的监听事件。

1.使用委托:

button.Click += delegate {

  button.Text = string.Format (“{0} clicks!”, count++);

};

2:使用Lamda表达式 :

button.Click += (s, e) =>{ 

     button.Text = string.Format (“{0} clicks!”, count++);

};

3.Xamarin android单选按钮监听事件:

namespace App914
{
[Activity(Label = "App914", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity,IOnCheckedChangeListener
{
int count = 1;

/// <summary>
/// 实现OnCheckedChangeListener的接口
/// </summary>
/// <param name="group"></param>
/// <param name="checkedId"></param>
public void OnCheckedChanged(RadioGroup group, int checkedId)
{
RadioButton rdBtn = (RadioButton)FindViewById(checkedId);
Toast.MakeText(this, rdBtn.Text, ToastLength.Short).Show();
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
RadioGroup rg = FindViewById<RadioGroup>(Resource.Id.rg);
rg.SetOnCheckedChangeListener(this);
}
}
}

布局文件我就不贴了,注意1.使用RadioGroup包含两个或者多个RadioButton ,,注意RadioGroup,RadioButton每个ID都必须要写上2.实现RadioGroup单击事件的接口
IOnCheckedChangeListener

4.Xamarin android按钮监听事件:



namespace App914
{
[Activity(Label = "App914", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity,View.IOnClickListener
{
int count = 1;
public void OnClick(View v)
{
Button btn = FindViewById<Button>(Resource.Id.MyButton);
btn.Text =string.Format( "实现xamarin android单击监听事件{0}",count++);
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);

// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.SetOnClickListener(this);
}
}
}
普通按钮实现单击事件的监听,注意接口是IOnClickListener

5.Xamarin android按钮监听事件:

namespace App914
{
[Activity(Label = "App914", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity, CompoundButton.IOnCheckedChangeListener
{
public void OnCheckedChanged(CompoundButton compoutButton,Boolean b)
{
if (compoutButton.Checked)
{
Toast.MakeText(this,compoutButton.Text.ToString(),ToastLength.Long).Show();
}
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
CheckBox cb_1 = (CheckBox)FindViewById(Resource.Id.cb_one);
CheckBox cb_2 = (CheckBox)FindViewById(Resource.Id.cb_two);
CheckBox cb_3 = (CheckBox)FindViewById(Resource.Id.cb_three);

cb_1.SetOnCheckedChangeListener(this);
cb_2.SetOnCheckedChangeListener(this);
cb_3.SetOnCheckedChangeListener(this);
}
}
}


多选按钮的监听事件布局文件我就不贴出来,同样是要注意的几点和RadioButton的监听事件一样

总结:

虽然说在xamarin中事件的监听用的不多,和lamda、delegate比起来也不方便,但是非常有必要了解一下,新手学xamarin的时候监听还是很有必要学一下的,不要的话参考菜鸟上的android教程不易理解,毕竟java android中就是用的监听,同时要注意的是每个元素的监听事件所实现的接口不一样,这是要注意的一点