1. 程式人生 > >Xamarin.Android多介面

Xamarin.Android多介面

一、準備

二、介面

1.開啟Resources/layout/Main.axml檔案,並在Call Button下方繼續加入一個按鈕,並設定其id為@+id/CallHistoryButton同時設定Text為@string/callHistory(這個其實是一個字串資源的識別符號,後面我們會新增該資源):

三、資源

1.開啟Resources/values/Strings.xml檔案

2.並在其中加入一個name為callHistory的字串資源:

3.回到Main.axml可以看到最後一個button顯示的字串變掉了:

4.之前的Call button是通過程式碼的方式禁用的,這次我們將CallHistory Button通過屬性該改變:

可以看到按鈕被禁用了:

四、程式碼

1.右擊專案,新建一個名為CallHistoryActivity的活動:

2.開啟剛才新建的活動,修改該活動的標題名稱,繼承的類並顯示傳遞過來的字串陣列:

 1 namespace Phoneword_Droid
 2 {
 3     [Activity(Label = "@string/callHistory")]
 4     public class CallHistoryActivity : ListActivity
 5     {
 6         protected override void
OnCreate(Bundle bundle) 7 { 8 base.OnCreate(bundle); 9 //從意圖中獲取傳遞過來的引數 10 var phoneNumbers = Intent.Extras.GetStringArrayList("phone_numbers") ?? new string[0]; 11 12 //將字串陣列顯示到列表控制元件中(因為繼承的是ListActivity所以整個檢視就是一個列表) 13 this.ListAdapter = new
ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, phoneNumbers); 14 15 //關於ArrayAdapter的第二個引數,其實就是指定列表中每個項的檢視,後面我們會通過自定義的方式控制列表的項 16 } 17 } 18 }
View Code

3.回到MainActivity.cs中,既然要顯示歷史記錄,那麼自然就必須要能夠儲存所以我們需要定義一個變數:

1     [Activity(Label = "Phoneword_Droid", MainLauncher = true, Icon = "@drawable/icon")]
2     public class MainActivity : Activity
3     {
4         static readonly List<string> phoneNumbers = new List<string>();
View Code

4.然後還要為callHistoryButton繫結監聽事件,以便開啟另一個活動(在OnCreate後面繼續追加):

1             Button callHistoryButton = FindViewById<Button>(Resource.Id.CallHistoryButton);
2             callHistoryButton.Click += (e, t) =>
3             {
4                 //指定意圖需要開啟的活動
5                 var intent = new Intent(this, typeof(CallHistoryActivity));
6                 //設定意圖傳遞的引數
7                 intent.PutStringArrayListExtra("phone_numbers", phoneNumbers);
8                 StartActivity(intent);
9             };
View Code

5.我們缺少一個新增歷史記錄的方法,這裡我們應該將其放入對話方塊的Call方法中,這樣只要撥打了的電話才會進入到歷史記錄中:

 1                 //撥打按鈕
 2                 callDialog.SetNeutralButton("Call", delegate
 3                 {
 4                     //將電話加入到歷史記錄列表中
 5                     phoneNumbers.Add(translatedNumber);
 6 
 7                     //如果callHistoryButton的定義在這段程式碼後面將會出錯,所以我們這個時候需要將
 8                     //Button callHistoryButton = FindViewById<Button>(Resource.Id.CallHistoryButton); 程式碼提前
 9                     callHistoryButton.Enabled = true;
10 
11                     //使用意圖撥打電話
12                     var callIntent = new Intent(Intent.ActionCall);
13 
14                     //將需要撥打的電話設定為意圖的引數
15                     callIntent.SetData(Android.Net.Uri.Parse("tel:" + translatedNumber));
16                     
17                     StartActivity(callIntent);
18                 });
View Code

五、執行