1. 程式人生 > >Mono for Android—初體驗之“電話撥號器”

Mono for Android—初體驗之“電話撥號器”

1、Main.axml檔案:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <EditText
        android:inputType="phone"
        android:layout_width="match_parent"   //填充父控制元件大小
        android:layout_height="wrap_content"  //根據內容自動拉伸
        android:id="@+id/etphoneNum" />
    <Button
        android:text="Button"
        android:layout_width="100.0dp"  //dp,與密度無關的畫素,一種基於螢幕密度的抽象單位。在每英寸160點的顯示器上,1dp="1px";
        android:layout_height="wrap_content"
        android:id="@+id/btnSend"
        android:layout_marginRight="0.0dp" />
</LinearLayout>

2、Activity1.cs檔案:

namespace AndroidDemo {    

/// <summary>    

/// 標籤AndroidDemo將出現在Android應用程式視窗中;MainLauncher批註,其表明了Activity是應用程式的主要啟動物件;Icon是程式圖示    

/// </summary>    

public class Activity1 : Activity  //activity活動,一個“活動”就是一個用來完成單個任務有的使用者介面元件    

{        

        EditText etphoneNum;        

         Button btnSend;        

      protected override void OnCreate(Bundle bundle)

     {            

            base.OnCreate(bundle);//初始化資源包

            // Set our view from the "main" layout resource            

           SetContentView(Resource.Layout.Main);//載入檢視

            btnSend = this.FindViewById<Button>(Resource.Id.btnSend);            

            etphoneNum = this.FindViewById<EditText>(Resource.Id.etphoneNum);

            btnSend.Click += btnSend_Click;

        }

        void btnSend_Click(object sender, EventArgs e)        

       {            

            string phoneNum = etphoneNum.Text.Trim();            

           if (phoneNum.Length == 0)

          {                

                     Toast.MakeText(this, "請輸入手機號", ToastLength.Long).Show();                

                     return;            

            }            

          //Intent myIntent = new Intent();//建立一個意圖            

         //myIntent.SetAction(Intent.ActionCall);//設定行為是“打電話”            

         //myIntent.SetData(Android.Net.Uri.Parse("tel:"+phoneNum));//設定資料,資料即為電話號碼,注意格式:tel:123456***            

          var myIntent = new Intent(Intent.ActionCall,Android.Net.Uri.Parse("tel:"+phoneNum));

            StartActivity(myIntent);//開始活動        

        }    

   }

}

3、最後,別忘設定許可權,只有擁用CALL_PHONE許可權才能實現撥打電話

 可以右擊“專案”,選擇“屬性”,即可開啟Android Manifest清單,在Required permissions下選擇“CALL_PHONE”即可。

<users-permission android:name="android.permission.CALL_PHONE"/>