一.新建一个空的工程
二.在主界面中添加一个按钮
三.新建一个空的activity,并命名为TheAty
四.修改MainActivity.java中的onCreate函数
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btnStartAty).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, TheAty.class); // i.putExtra("data", "hello android"); Bundle b = new Bundle(); b.putString("name","jikexueyuan"); b.putInt("age",2); i.putExtras(b); startActivity(i); } });
五.在TheAty的布局文件中给textView加上id号
<TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv"/>
六.修改TheAty的源代码文件中的onCreate函数
private TextView tv; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_the_aty); Intent i = getIntent(); Bundle data = i.getExtras(); tv = (TextView)findViewById(R.id.tv); // tv.setText(i.getStringExtra("data")); tv.setText(String.format("name=%s,age=%d",data.getString("name"),data.getInt("age"))); }
七.运行结果
ps:另一种传递Bundle的方式
//i.putExtras(b); //在MainActivity.java中传递Bunble参数b i.pushExtra("data",b); //在TheAty.java中获取Bunble参数 Bunble data = i.getBunbleExtra("name");