*/要想類比一個打電話程式,我們需要的是什麼呢?
1.畫出Android的UI圖
2.介面搭載
在UI介面中我們的設計中,分析發現String字串有兩個,一個text文字框,一個button。
首先在res-values-strings.xml中添加兩個字串
<?xml version="1.0" encoding="utf-8"?><resources> <string name="hello">Hello World, MyPhoneActivity!</string> <string name="app_name">MyPhone</string><string name="input_info">請輸入手機號碼</string><string name="button_caption">撥出</string></resources>
其次在res-layout-main.xml中添加布局介面
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- 添加TextView組件--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/input_info" /> <!-- 添加EditText組件 --> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/phone_number" /> <!-- 添加Button按鈕 --> <Button android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "@string/button_caption" android:id="@+id/dial_btn" /></LinearLayout>
ok,介面搭建完成,下一步需要做什麼呢?
3.
package cn.class3g.activity;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;/** * 建立Activity的要點: * 1.一個activity就是一個類,並且這個類要繼承Activity * 2.重寫onCreate方法 * 3.每一個Activity都需要在AndroidManifest。xml中進行配置 * 4.在main.xml進行添加必要的控制項 * */public class MyPhoneActivity extends Activity { //找到所寫的控制項EditText numberEt;Button dialBtn;//重寫onCreate方法 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findViews(); dialBtn.setOnClickListener(myListener); } //取出控制項內容 private void findViews(){ numberEt = (EditText) this.findViewById(R.id.phone_number); dialBtn = (Button) this.findViewById(R.id.dial_btn); } private OnClickListener myListener = new Button.OnClickListener(){ @Overridepublic void onClick(View v) {//調用系統的撥號服務實現電話撥打功能String phone_number = numberEt.getText().toString();phone_number = phone_number.trim();if(phone_number != null && !phone_number.equals("")){//封裝一個撥打到電話的intent,並且將電話號碼封裝成一個Uri對象傳入Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phone_number));MyPhoneActivity.this.startActivity(intent);//內部類}} };}
些到這裡很多同學就認為,是不是可以打電話了呢?其實不是的,因為還涉及許可權問題,那麼如何設定許可權呢?
在AndroidManifest.xml中修改許可權,可以直接添加<uses-permission android:name="android.permission.CALL_PHONE"/>
也可以使用
編輯器開啟
在許可權編輯器編輯
選擇撥號許可權
儲存即可。
run as -android application
如果有真機的,可以直接在真機中測試,本人測試沒有問題。
如果沒有真機,可以開兩個模擬器,一個模擬器中安裝本程式,另一根據模擬器號碼,撥打到電話。
,模擬器號碼為5556
如,可以看到MyPhone的應用程式
點擊運行
在輸入框中輸入5556,點擊撥打
類比打電話程式實現到這裡就寫完了!