xamarin android 中button的写法(入坑第一天)
刚开始用xamarin写安卓端,之前没有接触过安卓开发,只做过c#的winform开发。
新手必须了解的:
1、调试有两种方式,一种用xamarin自带的仿真程序管理器(avd),还有一种就是手机真机,avd必须先启动,因为启动要一段时间,真机就简单了,avd占电脑资源较多,硬件慢的不建议使用avd模式,建议使用真机直接调试,我的电脑CPU是4核的酷睿(14年的机子),8g内存,机械硬盘,简单的程序部署到真机大概30秒左右。如果调试下拉菜单里没有你的手机,估计是安卓版本或者api的版本不对,去属性里的androi清单里修改就好了。
2、本人从c#转过来,很多不适应,之前只要双击button就自动生成click的方法,现在不行了,必须手写,先定义,再初始化,再写方法,全部都是手写,让我晕30秒。。。,直接上代码图,button方法很多种,我这个只是其中一个,初始化后可以用delegate或者Lamda都可以,后面有代码。
3、部署或者调试失败,可以从几个地方着手 检查,1、电脑是否有装手机的驱动,最简单的 方法就是电脑和手机都装个360手机助手,电脑能和手机连上后,说明电脑上有手机的驱动了,然后看看vs调试的地方有没有手机的型号,如果没有需要检查下手机端开发模式启用没,电脑usb供电是否够(360能连上手机,就表示够)。
源码可以去这里下载:http://download.****.net/download/u014194297/10174658
文末来个福利吧,增减按钮的cs源码
namespace App7
{
[Activity(Label = "App7", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
this._initialize();
//个人感觉这两种写法不如直接写click类直观
//委托 button写法1
Button btn_delegate = FindViewById<Button>(Resource.Id.button3);
btn_delegate.Click += delegate { btn_delegate.Text = string.Format("{0} click", counter++); };
//lamda button写法2
Button btn_lamda = FindViewById<Button>(Resource.Id.button4);
btn_lamda.Click += (sender, e) => { btn_lamda.Text = string.Format("{0} click", counter++); };
}
private Button btn_add;
private Button btn_sub;
private TextView text_result;
private int counter;
//写法3
private void _initialize() //定义功能类
{
this._initialize_controls();
this.btn_add.Click += new System.EventHandler(this.ButtonClick_add);
this.btn_sub.Click += new System.EventHandler(this.ButtonClick_sub);
}
private void _initialize_controls() //定义功能类与前端对应的控件
{
this.btn_add = FindViewById<Button>(Resource.Id.button1);
this.btn_sub = FindViewById<Button>(Resource.Id.button2);
this.text_result = FindViewById<TextView>(Resource.Id.textView1);
}
protected void ButtonClick_add(object sender, System.EventArgs args)
{
this.counter += 1;
this.text_result.Text = "按钮被点击了" + this.counter.ToString() + "次!!!";
}
private void ButtonClick_sub(object sender, System.EventArgs args)
{
this.counter -= 1;
this.text_result.Text = "按钮被点击了" + this.counter.ToString() + "次!!!";
}
}
}