练习用内部类方式设置点击事件来实现直接拨打电话功能
package com.hanqi.dianhuabohaoqi; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText et_number; Button bt_1; String number; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt_1=(Button)findViewById(R.id.bt_1); et_number=(EditText)findViewById(R.id.et_number); bt_1.setOnClickListener(new callphone()); } class callphone implements View.OnClickListener { public void onClick(View v) { switch (v.getId()) { case R.id.bt_1: number=et_number.getText().toString().trim(); if (number.length()==0) { Toast.makeText(MainActivity.this, "请输入电话号码", Toast.LENGTH_SHORT).show(); } if (number==null)return; Intent intent = new Intent(Intent.ACTION_CALL); Uri uri=Uri.parse("tel:"+number); intent.setData(uri); try { startActivity(intent); }catch (Exception e) { e.printStackTrace(); } break; } } } }
<?xml version="1.0" encoding="utf-8"?> <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.hanqi.dianhuabohaoqi.MainActivity"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="phone" android:id="@+id/et_number" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="拨打电话" android:id="@+id/bt_1" android:layout_alignRight="@+id/et_number" /> </RelativeLayout>