ActivityForResult

androidActivity之间的跳转不只是有startActivity(Intent i)的,startActivityForResult(Intentintent, int requestCode)也是常用的方法。


其作用是可以用onActivityResult(int requestCode, int resultCode, Intent data)方法获得请求Activity结束之后的操作。
需要注意三个方法: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(serverIntent, REQUEST_CODE_01);//跳转至ToB
}else{
Intent intent = new Intent(this, ToC.class);
startActivityForResult(serverIntent, 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)的参数,第一个Intent不用说了,需要注意的是第二个,我们用的是REQUEST_CODE_01和REQUEST_CODE_02,其实这个是我们自己定义的一个int型常量,用于标记的,具体作用可在onActivityResult方法里看到,用于判断是从哪个Activity返回的。
ToB:
Intent intent = new Intent();
intent.putExtra(key, value);
setResult(Activity.RESULT_OK, intent);
finish();//结束之后会将结果传回From
ToC:
Intent intent = new Intent();
intent.putExtra(key, value);
setResult(Activity.RESULT_OK, intent);
finish();//结束之后会将结果传回From
setResult的第一个参数对应上面onActivityResult的第二个参数,注意别把onActivityResult的第一个参数与第二个参数搞混淆了,一个是请求标记,一个是返回标记。

以下为android Developer的解释:

Starting an activity for a result
Sometimes, you might want to receive a result from the activity that you start. In that case, start the activity by calling startActivityForResult()
(instead of startActivity()). To then receive the result from the subsequent activity, implement the onActivityResult()callback method. When the subsequent activity is done, it returns a result in an Intent to your onActivityResult() method.

For example, perhaps you want the user to pick one of their contacts, so your activity can do something with the information in that contact. Here's how you can create such an intent and handle the result:

private void pickContact() {      // Create an intent to "pick" a contact, as defined by the content provider URI      Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);      startActivityForResult(intent, PICK_CONTACT_REQUEST);  }    @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {      // If the request went well (OK) and the request was PICK_CONTACT_REQUEST      if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {          // Perform a query to the contact's content provider for the contact's name          Cursor cursor = getContentResolver().query(data.getData(),          new String[] {Contacts.DISPLAY_NAME}, null, null, null);          if (cursor.moveToFirst()) { // True if the cursor is not empty              int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);              String name = cursor.getString(columnIndex);              // Do something with the selected contact's name...          }      }  }  

This example shows the basic logic you should use in your onActivityResult() method in order to handle an activity result. The first condition checks whether the request was successful—if it was, then the resultCode will be RESULT_OK—and whether the request to which this result is responding is known—in this case, the requestCode matches the second parameter sent with startActivityForResult(). From there, the code handles the activity result by querying the data returned in an Intent(the data parameter).What happens is, aContentResolver performs a query against a content provider, which returns a Cursor that allows the queried data to be read. For more information, see the Content Providersdocument.

For more information about using intents, see the Intents and Intent Filters document.


两个Activity:ReceiveResult和SendResult。在ReceiveResult中实现onActivityResult(),在此方法中处理SendResult中返回的结果。

注意:

1)在ReceiveResult中定义RequestCode

2)调用startActivityForResult(),用来获取结果

3)在SendResult中用调用setResult()

具体代码如下:

ReceiveResult:

  1. public class ReceiveResult extends Activity {  
  2.     @Override  
  3.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  4.         // TODO Auto-generated method stub  
  5.           
  6.         if(requestCode == GET_CODE){  
  7.             Editable text = (Editable)mTextView.getText();  
  8.               
  9.             if(resultCode == RESULT_CANCELED)  
  10.                 text.append("Cancel");  
  11.             else{  
  12.                 text.append(data.getAction());  
  13.             }  
  14.         }  
  15.     }  
  16.     /** Called when the activity is first created. */  
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.main);  
  21.           
  22.         Button getResult = (Button)findViewById(R.id.getButton);  
  23.           
  24.         getResult.setOnClickListener(mGetResult);  
  25.           
  26.         mTextView = (TextView)findViewById(R.id.results);  
  27.         mTextView.setText(mTextView.getText(), TextView.BufferType.EDITABLE);  
  28.           
  29.     }  
  30.       
  31.     /* 
  32.      * GET_CODE requestCode 
  33.      */  
  34.     private final int GET_CODE = 0;  
  35.       
  36.     private OnClickListener mGetResult = new OnClickListener(){  
  37.         public void onClick(View v){  
  38.             Intent i = new Intent(ReceiveResult.this, SendResult.class);  
  39.             startActivityForResult(i, GET_CODE);  
  40.         }  
  41.     };  
  42.       
  43.     private TextView mTextView;  
  44. }  

 

SendResult:

  1. public class SendResult extends Activity {  
  2.     @Override  
  3.     protected void onCreate(Bundle savedInstanceState) {  
  4.         // TODO Auto-generated method stub  
  5.         super.onCreate(savedInstanceState);  
  6.           
  7.         setContentView(R.layout.sendresult);  
  8.           
  9.         Button button1 = (Button)findViewById(R.id.button1);  
  10.         Button button2 = (Button)findViewById(R.id.button2);  
  11.           
  12.         button1.setOnClickListener(mButton1);  
  13.         button2.setOnClickListener(mButton2);  
  14.     }  
  15.       
  16.     private OnClickListener mButton1 = new OnClickListener(){  
  17.         public void onClick(View v){  
  18.             setResult(RESULT_OK, (new Intent()).setAction("Button1!"));  
  19.             finish();  
  20.         }  
  21.     };  
  22.       
  23.     private OnClickListener mButton2 = new OnClickListener(){  
  24.         public void onClick(View v){  
  25.             setResult(RESULT_OK, (new Intent()).setAction("Button2!"));  
  26.             finish();  
  27.         }  
  28.     };  
  29.                                                            
  30. }  

 

main.xml:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:gravity="center_horizontal"  
  7.     >  
  8. <TextView    
  9.     android:layout_width="fill_parent"   
  10.     android:layout_height="wrap_content"   
  11.     android:text="@string/hello"  
  12.     />  
  13.       
  14.     <TextView android:id="@+id/results"  
  15.         android:layout_width="match_parent" android:layout_height="10dip"  
  16.         android:layout_weight="1"  
  17.         android:paddingBottom="4dip"  
  18.         android:background="@drawable/green">  
  19.     </TextView>  
  20.       
  21. <Button  
  22.     android:id="@+id/getButton"  
  23.     android:text="@string/getResult"  
  24.     android:layout_width="wrap_content"  
  25.     android:layout_height="wrap_content"  
  26.     />  
  27. </LinearLayout>  

 

sendresult.xml:

[c-sharp] view plain copy print ?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:gravity="center_horizontal"  
  7.     >  
  8.       
  9. <Button  
  10.     android:id="@+id/button1"  
  11.     android:text="@string/sendResult_1"  
  12.     android:layout_width="wrap_content"  
  13.     android:layout_height="wrap_content"  
  14.     />  
  15.       
  16.     <Button  
  17.     android:id="@+id/button2"  
  18.     android:text="@string/sendResult_2"  
  19.     android:layout_width="wrap_content"  
  20.     android:layout_height="wrap_content"  
  21.     />  
  22. </LinearLayout>  

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值