在Android中 ,我们知道,两个activity之间通讯要用到Intent类,传递简单数据的方式我们也已经知道了。那么,如何在两个activity之间传递数据包呢,这就要用到我们的Bundle类了。
下面是代码演示,信息的发起者为MainActivity,接受者为Target类。
MainActivity类:
1 package com.example.sendsbundle; 2 3 import android.content.Intent; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 8 public class MainActivity extends AppCompatActivity { 9 10 @Override 11 protected void onCreate(Bundle savedInstanceState) { 12 super.onCreate(savedInstanceState); 13 setContentView(R.layout.activity_main); 14 15 findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { 16 @Override 17 public void onClick(View view) { 18 Intent intent =new Intent(MainActivity.this,Target.class); 19 Bundle bundle=new Bundle(); 20 bundle.putInt("data",123); 21 bundle.putString("name","Hogwarts"); 22 intent.putExtras(bundle); 23 startActivity(intent); 24 } 25 }); 26 } 27 }
activity_main.xml:
1 <?xml version="1.0" encoding="utf-8"?> 2 <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context="com.example.sendsbundle.MainActivity"> 8 9 <Button 10 android:id="@+id/button" 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 android:text="Send!" 14 app:layout_constraintBottom_toBottomOf="parent" 15 app:layout_constraintLeft_toLeftOf="parent" 16 app:layout_constraintRight_toRightOf="parent" 17 app:layout_constraintTop_toTopOf="parent" /> 18 19 </android.support.constraint.ConstraintLayout>
Target类:
1 package com.example.sendsbundle; 2 3 import android.content.Intent; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.widget.TextView; 7 8 public class Target extends AppCompatActivity { 9 private TextView textview; 10 @Override 11 protected void onCreate(Bundle savedInstanceState) { 12 super.onCreate(savedInstanceState); 13 setContentView(R.layout.activity_target); 14 15 Intent i=getIntent(); 16 Bundle b=i.getExtras(); 17 textview=(TextView)findViewById(R.id.tv); 18 textview.setText(String.format("data=%d name=%s",b.getInt("data"),b.getString("name"))); 19 } 20 }
activity_target.xml:
1 <?xml version="1.0" encoding="utf-8"?> 2 <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context="com.example.sendsbundle.Target"> 8 9 <TextView 10 android:id="@+id/tv" 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 /> 14 15 </android.support.constraint.ConstraintLayout>
测试结果如图: