4.Activity与Activity之间的转跳
在软件应用的开发中肯定会有多个Activity 这样它们之间就会存在相互转跳的关系 转跳的实现方式还是使用Intent 然后startActivity ,当然转跳的话是可以带数据过去的。比如从A跳到B 可以把A中的一些数据通过Intent传递给B 。
在软件应用的开发中肯定会有多个Activity 这样它们之间就会存在相互转跳的关系 转跳的实现方式还是使用Intent 然后startActivity ,当然转跳的话是可以带数据过去的。比如从A跳到B 可以把A中的一些数据通过Intent传递给B 。
读下面这段代码 大家会发现intent与bandle 传递数值的方式基本一样为什么还要分成两个呢? 确实他们两个传递的数值的方式非常类似, 他们两个的区别就是Intent属于把零散的数据传递过去 而bundle则是把零散的数据先放入bundle 然后在传递过去。我举一个例子 比如我们现在有3个activity A.B.C 须要把A的数据穿给B然后在穿给C ,如果使用intent一个一个传递 须要在A类中一个一个传递给B 然后B类中获取到所有数值 然后在一个一个传递给C 这样很麻烦 但是 如果是bundle的话 B类中直接将bundler传递给C 不用一个一个获得具体的值 然后在C类中直接取得解析数值。
传递
view plain
/**Activity之间传递值**/
Button botton3 = (Button)findViewById(R.id.button3);
botton3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(mContext,ShowActivity.class);
//使用intent.putExtra()直接传递
intent.putExtra("name", "雨松MOMO");
intent.putExtra("age", 25);
intent.putExtra("boy", true);
//把数值放进bundle 然后在把整个bundle通过intent.putExtra()传递
Bundle bundle = new Bundle();
bundle.putString("b_name", "小可爱");
bundle.putInt("b_age", 23);
bundle.putBoolean("b_boy", false);
//在这里把整个bundle 放进intent中
intent.putExtras(bundle);
//开启一个新的 activity 将intent传递过去
startActivity(intent);
}
});
接收
view plain
public class ShowActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.my);
Intent intent = getIntent();
String name = intent.getStringExtra("name");
//第二个参数为默认值 意思就是如果在intent中拿不到的话
//就用默认值
int age = intent.getIntExtra("age", 0);
boolean isboy = intent.getBooleanExtra("boy", false);
TextView textView0 = (TextView)findViewById(R.id.text0);
textView0.setText("姓名 " + name + "年龄 " + age + "男孩? " + isboy);
Bundle bundle = intent.getExtras();
name = bundle.getString("b_name");
//第二个参数为默认值 意思就是如果在bundle中拿不到的话
//就用默认值
age = bundle.getInt("b_age",0);
isboy = bundle.getBoolean("b_boy", false);
TextView textView1 = (TextView)findViewById(R.id.text1);
textView1.setText("姓名 " + name + "年龄 " + age + "男孩? " + isboy);
super.onCreate(savedInstanceState);
}
}