要求:頁面1跳轉到頁面2,頁面2再返回頁面1同時返回數據
頁面1添加如下代碼:
Intent intent = new Intent(); intent.setClass(頁面1.this, 頁面2.class); Bundle bundle = new Bundle(); intent.putExtras(bundle);//將Bundle添加到Intent,也可以在Bundle中添加相應數據傳遞給下個頁面,例如:bundle.putString("abc", "bbb"); startActivityForResult(intent, 0);// 跳轉並要求返回值,0代表請求值(可以隨便寫)
頁面2接收數據添加代碼如下:
Intent intent = this.getIntent(); Bundle bundle = intent.getExtras(); bundle.putString("aaa", "back");//添加要返回給頁面1的數據 intent.putExtras(bundle); this.setResult(Activity.RESULT_OK, intent);//返回頁面1 this.finish();
頁面1接收返回數據:(需要重寫onActivityResult)
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 0 && resultCode == Activity.RESULT_OK) { Bundle bundle = data.getExtras(); gameView.backString = bundle.getString("aaa"); Toast.makeText(this, backString, Toast.LENGTH_SHORT).show(); } }