Android自學筆記-4-簡單電話撥號器

來源:互聯網
上載者:User

動手寫一個簡單的電話撥號器,功能在文字框中輸入電話號碼,點擊撥打按鈕撥打到電話。(小例子沒有對號碼正確性進行驗證)

1 建立一個android工程,名字就叫做電話撥號器。由於ADT的新版本支援中文的項目,所以可以直接使用中文。工程的基本目錄如下:

2 開發撥打到電話的介面。

開啟工程的res/layout/activity_main.xml檔案,這時候右邊會出現一個可視化的介面工具。在android中所有的介面布局都是寫在xml裡面的,這裡雖然可以直接拖動對應的控制項就可以,但是最後產生的還是xml檔案。簡單的布局如下:

3 編寫代碼,處理點擊事件,撥打到電話。

首先找到對應的按鈕對象,添加點擊事件,在點擊的時候擷取電話號碼,撥打到電話,代碼如下:

package com.mxy.dail;import android.app.Activity;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;public class MainActivity extends Activity {//定義變數private Button btnDail;private EditText phoneNumber;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                //使用findViewById 擷取按鈕和文字框對象 並進行類型的強制轉換        btnDail = (Button) findViewById(R.id.btn_dail);        //為按鈕添加監聽事件        btnDail.setOnClickListener(new MyListener());                phoneNumber = (EditText) findViewById(R.id.number);    }    private class MyListener implements OnClickListener{@Overridepublic void onClick(View v) {//擷取輸入的電話號碼EditText phoneNumber = (EditText) MainActivity.this.findViewById(R.id.number);String number = phoneNumber.getText().toString();//驗證電話號碼是否可用//想幹什麼Intent intent = new Intent();//具體想做什麼intent.setAction(Intent.ACTION_CALL);intent.setData(Uri.parse("tel:" + number));//使用這個需要在AndroidManifest.xml檔案中添加對應的許可權 android.permission.CALL_PHONEstartActivity(intent);}        }    }
4 添加對應的許可權

在AndroidManifest.xml檔案中添加撥打到電話的許可權,如果不添加此許可權程式啟動並執行時候將會崩潰,添加如下代碼:



5 運行

在項目上點擊右鍵,選擇Run As --> Android Application,選擇裝置運行、測試。


工程:http://pan.baidu.com/s/1gdwuybT

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.