1. 程式人生 > >xamarin android 中button的寫法(入坑第一天)

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.csdn.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() + "次!!!";
        }
    }
}