其实Activity间的传值就是通过Bundle,intent中也是自动生成了Bundle来传值,里面还有个onActivityResult()方法也可以传送数值。
如果一个Activity是由startActivityForResult启动的,那么这个activity在finish()后就会回调启动它的activity中的onActivityResult()方法。
下面是全部代码:
MainActivity.java
package com.kale.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(MainActivity.this,SecondActivity.class); //intent这时里面还没有bundle对象,所以系统会自动生成一个bundle对象,把数据放入bundle,然后把bundle给intent intent.putExtra("KEY", "VALUE"); Bundle bundle = new Bundle(); bundle.putString("KEY from bundle", "VALUE from bundle"); intent.putExtras(bundle); /*只要你是startActivityForResult(intent, INVITE_CODE); 这个方法启动的Activity2,当你finish()Activity2的时候 , 返回到Activity1中,它会自动调用onActivityResult这个方法, 然后你要传递的数据就在这发方法的Intent参数里面*/ startActivityForResult(intent, 123); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String result = data.getExtras().getString("requestKEY");//得到新Activity 关闭后返回的数据 System.out.println("返回的结果是:"+result); } }
SecondActivity.java
package com.kale.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; public class SecondActivity extends ActionBarActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second); Intent intent = getIntent(); System.out.println("value0 = "+intent.getStringExtra("KEY")); Bundle bundle = intent.getExtras(); String value01 = bundle.getString("KEY"); String value02 = bundle.getString("KEY from bundle"); System.out.println("value01 = "+value01); System.out.println("value02 = "+value02); Intent resultIntent = new Intent(); resultIntent.putExtra("requestKEY", "requestValue"); //设置返回数据 setResult(RESULT_OK, resultIntent);//设置给之前启动它的activity的一个返回码 finish(); } }