在android入门的案例中,除了HelloWorld这个经典案例,还有一个电话拨号器需要掌握,现在我就来个电话拨号器的示范,毕竟大牛也是从菜鸟进化而来的。
首先你应该知道自己要设置怎样的UI,然后创建android项目,然后在写可扩展标记语言XML,我们需要记住XML的标签是成对出现的,写完之后的代码如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
解释一下属性,LinearLayout 是线性布局,在eclipse上不能直接拖拽组件,当有多个组件,还要设置方向orientation
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="请输入您要输入的电话号码"
android:textSize="25sp" />
TextView是文本视图,你能写文字描述什么的,textSize是修改字体的属性
<EditText
android:id="@+id/e1"
android:layout_width="260dp"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="拨号"/>
<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="取消"/>
</LinearLayout>
</LinearLayout>
这就是简单的拨号视图,现在你可以来写java了,我们这个写的是可以把号码拨出去的应用,所以要有意图来执行
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
//设置全局变量
private EditText et1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//设置ID,定义点击事件
Button bt1=(Button)findViewById(R.id.b1);
Button bt2=(Button)findViewById(R.id.b2);
et1=(EditText)findViewById(R.id.e1);
//设置一个监视器
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取电话号码,转化为字符串,去空格
String number=et1.getText().toString().trim();
// TODO Auto-generated method stub
//设置一个意图进行拨打行动
Intent intent=new Intent(Intent.ACTION_DIAL);
//设置协议
//URI是全国资源标识符,自己定义路径,tel是必须小写的 intent.setData(Uri.parse("tel:"+number));
startActivity(intent);
if("".equals(number)){
//土司,在这里起到了警示作用,show()方法是直接展示出来 Toast.makeText(MainActivity.this,"bunengweikong",Toast.LENGTH_LONG).show();
}
}
});
}
}
好了,电话拨号器到了这里应该差不多了!