在android代码中,常用按钮点击事件是先创建按钮的点击事件,里面参数为本activity的上下文对象:bt_dail.setOnClickListener(this);
在activity里面实现OnClickListener接口,再实现其方法,然后调用点击要触发的事件......
这里运用的是个电话拨打事例,首先要加入电话拨打权限:
<uses-permission android:name="android.permission.CALL_PHONE"/>
代码:
activity_main.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: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=".MainActivity"
android:orientation="vertical" >
<EditText
android:text="@string/et_number"
android:id="@+id/et_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone" />
<Button
android:id="@+id/bt_dail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/dail" />
</LinearLayout>
package org.mtn.phonedemo;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
private Button bt_dail;
private EditText et_number;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_dail = (Button) findViewById(R.id.bt_dail);
et_number = (EditText) findViewById(R.id.et_number);
bt_dail.setOnClickListener(this);
}
public void callPhone()
{
String number = et_number.getText().toString().trim();
if(TextUtils.isEmpty(number))
{
Toast.makeText(getApplicationContext(), "号码不能为空", 0).show();
return ;
}
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
startActivity(intent);
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.bt_dail:
callPhone();
break;
}
}
}