使用Intent传递参数

本文介绍了在Android应用程序中使用Intent和Bundle进行数据传递的方法。详细解释了如何在不同Activity之间通过putExtra()方法和Bundle对象传递字符串、整型数据及自定义对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.使用PutExtra()传递参数
在mainActivity中设置Intent

Intent i = new Intent(MainActivity.this,AnotherAty.class);   
i.putExtra("name","john");
startActivity(i);

在第二个Activity中设置

Intent i = getIntent();
textView.setText(i.getStringExtra("data"));

2.使用Bundle传递参数

  1. 在mainActivity中设置
Intent i = new Intent(MainActivity.this,AnotherAty.class);
Bundle b = new Bundle();
b.putString("name","john");
b.putInt("age",2);
i.putExtras(b);
startActivity(i);

在第二个Activity中设置:

Intent i = getIntent();
Bundle data = i.getExtras();
textView.setText(String.format("name=%s,age=%d,name2=%s",
data.getString("name"),
data.getInt("age"),
data.getString("name1","leo")));
//第三个是使用默认的设置,当第三个name1为空是,选择默认的信息传递
  1. 也是使用Bundle传递参数

在MainActivity中这样设置

  Intent i = new Intent(MainActivity.this,AnotherAty.class);

                Bundle b = new Bundle();
                b.putString("name","john");
                b.putInt("age",2);
                i.putExtra("bundle",b);
                startActivity(i);

在另一个Activity中这样设置


        Intent i = getIntent();
        Bundle data = i.getBundleExtra("bundle");
        textView = (TextView) findViewById(R.id.text_view);
        textView.setText(String.format("name=%s,age=%d,name2=%s",data.getString("name"),data.getInt("age"),data.getString("name1","leo")));

传递值对象

使用Serializable序列化接口来实现:
先创建一个User类:

public class User implements Serializable {
    private String name;
    private int age;


    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public User(String name,int age){
        this.name = name;
        this.age = age;
    }

}

在MainActivity中写入:

Intent i = new Intent(MainActivity.this,AnotherAty.class);

                i.putExtra("user", new User("John",20));
                startActivity(i);

随后,在另一个Activity中:

 Intent i = getIntent();
        textView = (TextView) findViewById(R.id.text_view);
        User user = (User) i.getSerializableExtra("user");
        textView.setText(String.format("User info(name = %s,age = %d)",user.getName(),user.getAge()));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值