android中使用startActivityForResult回傳資料

來源:互聯網
上載者:User

 

假設:我這裡有兩個Activity:A和B,從A中向B中傳遞資料的時候採用的是Bundle封裝資料,然後從A中跳轉到B中,當B有需求將資料封裝起來回傳給A並跳回A。那麼A中接收資料時還要先判斷Bundle是否為空白,因為第一次訪問A的時候(即B還沒有回傳的時候),Bundle是為空白的,這樣顯然是比較麻煩的,不明智的做法。

 

還好startActivityForResult來做跳轉給了我們更好的解決辦法。

 

 

 

1.跳轉的時候不是採用startActivity(intent) 這個方法,而是startActivityForResult(intent, 0)。

 

 

 

 

Java代碼 

Intent intent=new Intent();  

intent.setClass(A.this, B.class);  

Bundle bundle=new Bundle();  

String str1="aaaaaa";   

bundle.putString("str1", str1);  

intent.putExtras(bundle);  

startActivityForResult(intent, 0);  

/這裡採用startActivityForResult來做跳轉,此處的0為一個依據,可以寫其他的值,但一定要>=0 

 

 Intent intent=new Intent();

 intent.setClass(A.this, B.class);

 Bundle bundle=new Bundle();

 String str1="aaaaaa";

 bundle.putString("str1", str1);

 intent.putExtras(bundle);

 startActivityForResult(intent, 0);

//這裡採用startActivityForResult來做跳轉,此處的0為一個依據,可以寫其他的值,但一定要>=0

 

2.重寫onActivityResult方法,用來接收B回傳的資料。

 

 

Java代碼 

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  

 switch (resultCode) { //resultCode為回傳的標記,我在B中回傳的是RESULT_OK  

   case RESULT_OK:  

       Bundle b=data.getExtras(); //data為B中回傳的Intent  

       String str=b.getString("str1");//str即為回傳的值  

       break;  

   default:  

       break;  

   }  

 } 

 

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

 switch (resultCode) { //resultCode為回傳的標記,我在B中回傳的是RESULT_OK

   case RESULT_OK:

       Bundle b=data.getExtras(); //data為B中回傳的Intent

       String str=b.getString("str1");//str即為回傳的值

       break;

   default:

       break;

   }

 } 

 

 

 

3.在B中回傳資料時採用setResult方法,並且之後要調用finish方法。

這樣當B中調用finish方法的時候,跳轉到A時會自動調用onActivityResult方法,來擷取B中回傳的intent了。 

 

 

 

Java代碼 

setResult(RESULT_OK, intent); //intent為A傳來的帶有Bundle的intent,當然也可以自己定義新的Bundle  

finish();//此處一定要調用finish()方法 

 

setResult(RESULT_OK, intent); //intent為A傳來的帶有Bundle的intent,當然也可以自己定義新的Bundle

finish();//此處一定要調用finish()方法www.2cto.com

 

這樣當B中調用finish方法的時候,跳轉到A時會自動調用onActivityResult方法,來擷取B中回傳的intent了。

摘自 Dream Idears

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.