首页 > 代码库 > 多个Activity参数传递

多个Activity参数传递

Activity转到other Activity


package cn.itcast.activitys;
import android.app.Activity;
public class MainActivity extends Activity
{
  super.onCreate(Bundle savedInstanceState);
  setContentView(R.layout.main);
}
public void openActivity(View v)
{
  Intent intent = new Intent();
  intent.setClassName("cn.itcast.activitys", "cn.itcast.activitys.OtherActivity");
  // 1>intent.setClass(this,OtherActivity.class);
  // 2>intent.setClassName(this, "cn.itcast.activitys.OtherActivity");
  // 3>intent.setComponent(new ComponentName(this,OtherActivity.class));
  // 4>Intent intent=new Intent(this,OtherActivity.class);    //独立一句
     /*附加数据方法一*/
intent.putExtra("name","李明");
intent.putExtra("age",5);
/*方法二*/
Bundle bundle= new Bundle();
bundle.putString("name","CC");
bundle.putInt("age",10);
intent.putExtras(bundle);
 
startActivity(intent);
}
OtherActivity:
package cn.itcast.activitys;
import android.app.Activity;
import android.os.Bundle;
public class OtherActivity extends Activity
{
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
setContentView(R.layout.otheractivity);
Intent intent = getIntent();   //用于激活它的意图对象
/*方法一*/
String name=intent.getStringExtra("name");
int age=intent.getIntExtra("age",0);
/*方法二*/
Bundle bundle = intent.getExtras();
String name=bundle.getString("name");
int age = bundle.getInt("age");
  }
}
OtherActivity关闭把数据返回给MainActivity
替换startActivity();为startActivityForResult(intent,200);   //请求码用来区分返回数据在哪个位置


处理得到的数据重写方法
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
  String result=data.getStringExtra("result");
  Toast.makeText(this,result,1).show();
}
OtherActivity:
public void closeActivity(View v)
{
  Intent data = http://www.mamicode.com/new Intent();
   data.putExtra("result","mmmccc");
   setResult(30,data);  //结果码用来表示返回数据在哪个位置
   this.finish();
}