虽然准确来说第一个应该是HelloWorld,不过还是跳过吧。
我的第一个程序是一个简单的电话拨号器。
程序思路
- 做出界面,包含一个提示文本和一个接受输入的文本框,然后一个确认按钮
- 然后给按钮加一个点击事件,获取输入的值进行拨号。
程序代码
- 布局
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="请输入号码:" />
<EditText
android:id="@+id/et_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btn_call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/et_number"
android:text="Call" />
- 主页加载时
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到输入框
tv_number = (EditText)findViewById(R.id.et_number);
//找到确认按钮按钮
Button btn_call = (Button)findViewById(R.id.btn_call);
//为按钮添加点击事件
btn_call.setOnClickListener(new MyClickList());
}
- 确认按钮事件
private class MyClickList implements android.view.View.OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//从输入框获取电话号码
String number = tv_number.getText().toString().trim();
//输入号码为控制符串时报出提示信息
if ("".equals(number)) {
Toast.makeText(MainActivity.this, "号码不能为空!", 1).show();
return;
}
//创建意图对象
Intent intent = new Intent();
//设置活动
intent.setAction(Intent.ACTION_CALL);
//设置数据
intent.setData(Uri.parse("tel:" + number));
//开启意图
startActivity(intent);
}
}
备注
- tv_number输入框需要设置为静态
- 需要在AndroidManifest.xml里面设置用户拨号权限