android小功能實現之撥打到電話

來源:互聯網
上載者:User

標籤:android開發   撥號器   撥打到電話   

建立一個Android工程。

一 布局
開啟main.xml修改內容如下:
<TextView  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:text="@string/mobile"/>  <EditText   android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:inputType="text"  android:id="@+id/mobile"  /><Button   android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:text="@string/button"  android:id="@+id/button"  />






二 定義字串
開啟strings.xml新增內容如下:
<string name="mobile">請輸入手機號</string>  <string name="button">撥號</string>


三 響應點擊事件
1 方法一(推薦)
開啟MainActivity.java,在onCreate函數中添加如下代碼:
public void onCreate(Bundle savedInstanceState){  super.onCreate(savedInstanceState);setContentView(R.layout.main);Button button = (Button) this.findViewById(R.button);button.setOnClickListener(new ButtonClickListener());}

定義一個內部類,來實現回調對象:
private final class ButtonClick implements View.OnClickListener{public void onClick(View v){EditText text = (EditText) findViewById(R.id.mobile);String num = text.getText().toString();Intent intent = new Intent();intent.setAction("android.intent.action.CALL");intent.setData(Uri.parse("tel:"+num));startActivity(intent);}}

內部類減少了檔案的載入,提高了虛擬機器載入軟體的速度。


2 方法二
public void onCreate(Bundle savedInstanceState){  super.onCreate(savedInstanceState);setContentView(R.layout.main);Button button = (Button) this.findViewById(R.button);button.setOnClickListener(new View.OnClickListener(){public void onClick(View v){EditText text = (EditText) findViewById(R.id.mobile);String num = text.getText().toString();Intent intent = new Intent();intent.setAction("android.intent.action.CALL");intent.setData(Uri.parse("tel:"+num));startActivity(intent);}});}


四 添加許可權
在Manifest.xml中添加許可權:
<uses-permission android:name="android.permission.CALL_PHONE"/> 

五 最佳化
每次點擊按鈕,就會執行onClick,都會執行這句代碼:
EditText text = (EditText) findViewById(R.id.mobile);
來尋找控制項,尋找很耗資源,所以我們可以將這句放在onCreate中,只執行一次。

android小功能實現之撥打到電話

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.