android Activity之间的跳转不只是有startActivity(Intent i)的,startActivityForResult(Intent intent, int requestCode)也是常用的
方法。
在一个主界面(主Activity)上能连接往许多不同子功能模块(子Activity上去),当子模块的事情做完之后就回到主界面,或许还同时返回一些子模块完成的数据交给主Activity处理。这个时候就要用到回调函数onActivityResult()。
需要注意三个方法:startActivityForResult(Intent intent, int requestCode),onActivityResult(int requestCode, int resultCode, Intent data),setResult(int resultCode, Intent data).
例如如下代码:从From跳转至ToB和ToC
From:
if(条件){
Intent intent = new Intent(this, ToB.class);
startActivityForResult(intent, REQUEST_CODE_01);//跳转至ToB
}else{
Intent intent = new Intent(this, ToC.class);
startActivityForResult(intent, REQUEST_CODE_02);//跳转至ToC
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode) {//请求标记
case REQUEST_CODE_01:
if(resultCode==Activity.RESULT_OK)
//do something
break;
case REQUEST_CODE_02:
//do something
break;
}
}
startActivityForResult(Intent intent, int requestCode)的参数,需要注意的是第二个,我们用的是REQUEST_CODE_01和REQUEST_CODE_02,其实这个是我们自己定义的一个int型常量,用于标记的,具体作用可在onActivityResult方法里看到,用于判断是哪个Activity传来的。
requestCode是请求标记, resultCode是返回标记。
ToB:
Intent intent = new Intent();
intent.putExtra(key, value);
setResult(Activity.RESULT_OK, intent);
finish();//结束之后会将结果传回From
这里的跳转回去,只能用setResult(int resultCode, Intent data)方法,否则会出错,无法从onActivityResult(int requestCode, int resultCode, Intent data)中的data接收到传回来的数据。
ToC:
Intent intent = new Intent();
intent.putExtra(key, value);
setResult(Activity.RESULT_OK, intent);
finish();//结束之后会将结果传回From
setResult的第一个参数对应上面onActivityResult的第二个参数。
实例的一个效果:
点击搜索按钮,找到DianXin。
源码:
- xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <TextView
- android:id="@+id/mTextView"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="我的联系人" />
- <EditText
- android:id="@+id/mEditText01"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="姓名"
- />
- <EditText
- android:id="@+id/mEditText02"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="电话号码"
- />
- <Button
- android:id="@+id/mButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="搜索"
- />
- LinearLayout>
- package com.xc.ex05_10;
- import android.app.Activity;
- import android.content.Intent;
- import android.database.Cursor;
- import android.net.Uri;
- import android.os.Bundle;
- import android.provider.ContactsContract;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.widget.Toast;
- public class EX05_10 extends Activity {
- private TextView mTextView;
- private Button mButton;
- private EditText mEditText01;
- private EditText mEditText02;
- //回传标志
- private static final int PICK_CONTACT_SUBACTIVITY = 2;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mTextView = (TextView)findViewById(R.id.mTextView);
- mEditText01 = (EditText)findViewById(R.id.mEditText01);
- mEditText02 = (EditText)findViewById(R.id.mEditText02);
- mButton = (Button)findViewById(R.id.mButton);
- mButton.setOnClickListener(new Button.OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- startActivityForResult(new Intent(Intent.ACTION_PICK,
- android.provider.ContactsContract.Contacts.CONTENT_URI),
- PICK_CONTACT_SUBACTIVITY);
- }
- });
- }
- //向新打开的Activity传递参数
- //resultCode为回传的标记
- //data为B(新打开的Activity)中回传的Intent
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- // TODO Auto-generated method stub
- try{
- switch (requestCode) {
- case PICK_CONTACT_SUBACTIVITY:
- final Uri uriRet = data.getData();
- if(uriRet != null){
- try{
- //必须要有android.permission.READ_CONTACTS权限
- Cursor c = managedQuery(uriRet, null, null, null, null);
- c.moveToFirst();
- String strName = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
- mEditText01.setText(strName);
- //取得联系人的电话
- int contactId = c.getInt(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
- Cursor phones = getContentResolver().query(
- ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
- null,
- ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "+ contactId,
- null, null);
- StringBuffer sb = new StringBuffer();
- int typePhone, resType;
- String numPhone;
- if(phones.getCount() > 0){
- phones.moveToFirst();
- typePhone = phones.getInt(
- phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
- numPhone = phones.getString(
- phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
- resType = ContactsContract.CommonDataKinds.Phone.getTypeLabelResource(typePhone);
- sb.append(getString(resType) + ":" + numPhone + "\n");
- mEditText02.setText(numPhone);
- }else {
- sb.append("no Phone number found");
- }
- Toast.makeText
- (this, sb.toString(), Toast.LENGTH_SHORT).show();
- }catch (Exception e) {
- mTextView.setText(e.toString());
- e.printStackTrace();
- }
- }
- break;
- default:
- break;
- }
- }catch (Exception e) {
- e.printStackTrace();
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
- }
- xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.xc.ex05_10"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk android:minSdkVersion="8" />
- <uses-permission android:name="android.permission.READ_CONTACTS"/>
- <application
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name" >
- <activity
- android:label="@string/app_name"
- android:name=".EX05_10" >
- <intent-filter >
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- intent-filter>
- activity>
- application>
- manifest>
例子②:
布局文件为两个按钮,不再给出。
- package com.example.intentproject;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.Toast;
- public class SenderActivity extends Activity{
- private static final int MY_REQUEST_CODE = 1;
- private Button sender;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.sender);
- sender = (Button)findViewById(R.id.sender);
- sender.setOnClickListener(new Button.OnClickListener() {
- @Override
- public void onClick(View v) {
- Intent intent = new Intent(SenderActivity.this, RecieverActivity.class);
- startActivityForResult(intent, MY_REQUEST_CODE);
- }
- });
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- switch(requestCode){
- case MY_REQUEST_CODE:
- // 取出数据
- String info=data.getStringExtra("data2");
- Toast.makeText(this, info, Toast.LENGTH_LONG).show();
- break;
- }
- switch (resultCode) {
- case Activity.RESULT_CANCELED:
- Toast.makeText(this, "处理:"+String.valueOf(Activity.RESULT_CANCELED), Toast.LENGTH_LONG).show();
- break;
- case Activity.RESULT_OK:
- Toast.makeText(this, "处理:"+String.valueOf(Activity.RESULT_OK), Toast.LENGTH_LONG).show();
- break;
- case Activity.RESULT_FIRST_USER:
- String info=data.getStringExtra("data2");
- Toast.makeText(this, info, Toast.LENGTH_LONG).show();
- break;
- default:
- break;
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
- }
- package com.example.intentproject;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.widget.Button;
- public class RecieverActivity extends Activity{
- private Button reciever;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.reciever);
- reciever = (Button)findViewById(R.id.reciever);
- Intent intent = new Intent();
- intent.putExtra("data2", "给你回送数据!礼尚往来!");
- this.setResult(Activity.RESULT_FIRST_USER, intent);
- }
- }
RecieverActivity.java中也可以写成:
- Intent intent=this.getIntent();
- //返回数据
- intent.putExtra("data2", "给你回送数据!礼尚往来!");
- this.setResult(Activity.RESULT_FIRST_USER, intent);
也可以在SenderActivity.java文件中一开始就传递参数,在按钮响应事件中写成:
- sender.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Intent intent = new Intent(SenderActivity.this,
- ReciverActivity.class);
- intent.putExtra("data", "给你发送数据!");
- // 这种启动方式 ,表示是有返回结果的
- SenderActivity.this.startActivityForResult(intent,
- MY_REQUEST_CODE);
- }
- });
RecieverActivity.java中写:
- Intent intent=this.getIntent();
- String info=intent.getStringExtra("data");
- Toast.makeText(this, info, Toast.LENGTH_LONG).show();
- //返回数据
- intent.putExtra("data2", "给你回送数据!礼尚往来!");
- this.setResult(Activity.RESULT_FIRST_USER, intent);