Android前端开发01:电话拨号器
·
一、Dial Number
设计一个拨号小程序,涉及findViewByID, OnClickListener等。
二、findViewByID
声明
根据控件id (Int)获取控件对象 (View)。
View android.app.Activity.findViewById(int id)
布局文件-控件id
在布局文件中设置控件id应标明其功能
<Button
android:id="@+id/bt_call"
<!-- @+id将id加入资源文件中 -->
android:text="Call" />
获取控件
ID可从资源R.id中引用。由于返回的是View对象,所以需要强制类型转换。
Button bt_call = (Button) findViewById(R.id.bt_call);
三、setOnClickListener
声明
设置点击事件监听器
void android.view.View.setOnClickListener(OnClickListener l)
除此之外还有各种时间的监听器,用法类似
实现
监听器应实现对应的接口,触发方法应当继承 @Override。另注意Intent类的调用及Uri的用法。
关于Uri的使用,详见https://www.jianshu.com/p/7690d93bb1a1。
private class MyListener implements OnClickListener {
@Override
public void onClick(View v) {
EditText et = (EditText) MainActivity.this.findViewById(R.id.et_number);
String number = et.getText().toString();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+number));
startActivity(intent);
}
}
四、Permission
调用Intent可能会产生Exception,检查Logcat是否有"requires android.permission.xxx"并加入相关权限
*五、Code
MainActivity.java
package com.example.dialnumber;
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;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt_call = (Button) findViewById(R.id.bt_call);
bt_call.setOnClickListener(new MyListener())bt_call;
bt_call.set
}
private class MyListener implements OnClickListener {
@Override
public void onClick(View v) {
EditText et = (EditText) MainActivity.this.findViewById(R.id.et_number);
String number = et.getText().toString();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+number));
startActivity(intent);
}
}
}
activity_main.xml
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.dialnumber.MainActivity" >
<EditText
android:id="@+id/et_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:inputType="phone"
android:textSize="24sp" >
<requestFocus />
</EditText>
<Button
android:id="@+id/bt_call"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/et_number"
android:layout_below="@+id/et_number"
android:layout_marginTop="32dp"
android:text="Call" />
</RelativeLayout>
更多推荐

所有评论(0)