模拟一个打电话程序
1.在设计中,分析会发现String字符串有两个,一个text文本框,一个button按钮。
首先在res/values/strings.xml中添加两个字符串.
代码如下:
<?xml version="1.0"encoding="utf-8"?>
<resources>
<string name="hello">Hello World, PhoneActivity!</string>
<string name="app_name">Phone</string>
<string name="input_info">请输入号码:</string>
<string name="dial_caption">拨号</string>
</resources>
2.在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
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/input_info"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id ="@+id/phone_number"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/dial_btn"
android:text="@string/dial_caption"
>
</Button>
</LinearLayout>
3.实现它
代码如下:
packagecn.class3g.activity;
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.EditText;
publicclass PhoneActivity extends Activity {
/** Called when the activity is firstcreated. */
EditText numberEt;
Button dialBtn;
public void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViews();
dialBtn.setOnClickListener(newOnClickListener() {
@Override
publicvoid 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 = newIntent(Intent.ACTION_CALL,Uri.parse("tel:"+phone_number));
PhoneActivity.this.startActivity(intent);
}
}
});
}
public void findViews(){
numberEt = (EditText)this.findViewById(R.id.phone_number);
dialBtn=(Button)this.findViewById(R.id.dial_btn);
}
}
4.设置权限。
然后就完成了。