Intent意图 可用于Activity之间的数据传递,一般可分为下面两种情况,从当前Activity传递到目标Activity后有无返回值:

1.传递后无返回值的情况:

在起始Activity中,发送数据protectedvoidonCreate(BundlesaveInstanceState){super.onCreate(saveInstanceState);setContentView(R.layout.thisactivity);Intentintent=newIntent();//设置起始Activity和目标Activity,表示数据从这个Activity传到下个Activityintent.setClass(ThisActivity.this,TargetActivity.class);//绑定数据intent.putExtra("username",username);//也可以绑定数组intent.putExtra("userpass",userpass);//打开目标ActivitystartActivity(intent);}在目标Activity中,接收数据:protectedvoidonCreate(BundlesaveInstanceState){super.onCreate(saveInstanceState);setContentView(R.layout.targetactivity);//获得意图Intentintent=getIntent();//读取数据Stringname=intent.getStringExtra("username");Stringpass=intent.getStringExtra("userpass);}也可以适用Bundle(捆)在起始Activity中,发送数据:protectedvoidonCreate(BundlesaveInstanceState){super.onCreate(saveInstanceState);setContentView(R.layout.thisactivity);Intentintent=newIntent();//设置起始Activity和目标Activity,表示数据从这个Activity传到下个Activityintent.setClass(ThisActivity.this,TargetActivity.class);//一次绑定多个数据Bundlebundle=newBundle();bundle.putString("username",username);bundle.putString("userpass",userpass);intent.putExtras(bundle);//打开目标ActivitystartActivity(intent);}在目标Activity中,接收数据:protectedvoidonCreate(BundlesaveInstanceState){super.onCreate(saveInstanceState);setContentView(R.layout.targetactivity);//获得意图Intentintent=getIntent();//读取数据Bundlebundle=intent.getExtras();Stringname=bundle.getString("username");Stringpass=bundle.getString("userpass");}

2.传递后有返回值的情况:

当需要从目标Activity回传数据到原Activity时,可以使用上述方法定义一个新的Intent来传递数据,也可以使用startActivityForResult (Intent intent, int requestCode);方法。

在起始Activity中,发送数据:protectedvoidonCreate(BundlesaveInstanceState){super.onCreate(saveInstanceState);setContentView(R.layout.thisactivity);Intentintent=newIntent();//设置起始Activity和目标Activity,表示数据从这个Activity传到下个Activityintent.setClass(ThisActivity.this,TargetActivity.class);//绑定数据intent.putExtra("username",username);//也可以绑定数组intent.putExtra("userpass",userpass);//打开目标ActivitystartActivityForResult(intent,1);}//需要重写onActivityResult方法protectedvoidonActivityResult(intrequestCode,intresultCode,Intentintent){super.onActivityResult(requestCode,resultCode,intent);//判断结果码是否与回传的结果码相同if(resultCode==1){//获取回传数据Stringname=intent.getStringExtra("name");Stringpass=intent.getStringExtra("pass);//对数据进行操作......}在目标Activity中,接收数据:protectedvoidonCreate(BundlesaveInstanceState){super.onCreate(saveInstanceState);setContentView(R.layout.targetactivity);//获得意图Intentintent=getIntent();//读取数据Stringname=intent.getStringExtra("username");Stringpass=intent.getStringExtra("userpass);//从EditText中获取新的数据给name和passname=editText1.getText().toString();pass=editText2.getText().toString()//数据发生改变,需要把改变后的值传递回原来的Activityintent.putExtra("name",name);intent.putExtra("pass",pass);//setResult(intresultCode,Intentintent)方法setResult(1,intent);//销毁此Activity,摧毁此Activity后将自动回到上一个Activityfinish();}