标签:
主要是把打电话这个按钮的相应代码写成一个方法,通过调用这个方法来使代码看起来更加简洁工整:
MainActivity.java的代码如下:
package com.example.dailcall; import android.support.v7.app.ActionBarActivity; import android.text.TextUtils; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View;//创建一个onClickListener接口的时候要导入这个包名 import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends ActionBarActivity { // 定义组建 private EditText et; private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et=(EditText) findViewById(R.id.et_number); //通过findViewById来查找组建名,绑定到定义的组建变量。 btn=(Button) findViewById(R.id.btn_dail); btn.setOnClickListener(new MyClickListener()); } private class MyClickListener implements OnClickListener{ @Override public void onClick(View v) { // TODO Auto-generated method stub callNumber(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } //把callNumber()这个动作写成一个私有的方法 private void callNumber() { Intent intent=new Intent(); String number=et.getText().toString().trim(); if (TextUtils.isEmpty(number)) { Toast.makeText(MainActivity.this, "电话号码不能为空!", 0).show(); return; } 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.dailcall.MainActivity" > <EditText android:id="@+id/et_number" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="phone" > <requestFocus /> </EditText> <Button android:id="@+id/btn_dail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/et_number" android:text="@string/dail" /> </RelativeLayout>
标签:
原文地址:http://www.cnblogs.com/anzhuoke/p/4515666.html