使用Bundle在Activity之间进行数据传递

Activity之间的数据传递分为:
1、直接使用Intent的putExtra进行不同类型的数据进行传递。

Intent intent=new Intent(FifstActivity.this,SecondActivity.class);
                intent.putExtra("test","text");
                startActivity(intent);
Intent intent=getIntent();
        String string=intent.getStringExtra("test");
         Toast.makeText(getBaseContext(), "" +string, Toast.LENGTH_SHORT).show();

2、使用Serializable传递一个可序列化的数据集合

EditText username = (EditText) findViewById(R.id.username);
                EditText passwd = (EditText) findViewById(R.id.passwd);
                RadioButton sex = (RadioButton) findViewById(R.id.male);
                String gender = sex.isChecked() ? "男" : "女";
                Person p=new Person(username.getText().toString(),passwd.getText().toString(),gender);
                Bundle data=new Bundle();
                data.putSerializable("person",p);
                Intent intent=new Intent(FifstActivity.this,SecondActivity.class);
                intent.putExtras(data);
                startActivity(intent);

但是使用这种方式,那么数据类Person就必须继承Serializable这个接口。

class Person implements Serializable

然后在需要使用数据的地方直接通过Key来获取值就可以了。

Intent intent=getIntent();
        Person p=(Person) intent.getSerializableExtra("person");
        Toast.makeText(getBaseContext(), "" + p.getUsername() + p.getPasswd() + p.getSex(), Toast.LENGTH_SHORT).show();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值