Activity传递参数——传递自定义数据类型

一.新建一个空的工程

二.在主界面中添加一个按钮

三.新建一个空的activity,并命名为TheAty

四.新建一个user类

//注意这里要实现Serializable,不然在传递参数时会出错
public class User implements Serializable{
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public User(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
}

五.修改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("user", (Serializable) new User("Mary",20));//注意这里要做强制类型转换
                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函数

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_the_aty);
        Intent i = getIntent();
        tv = (TextView)findViewById(R.id.tv);
       User user = (User) i.getSerializableExtra("user");//注意这里要做强制类型转换
        tv.setText(String.format("name=%s,age=%d",user.getName(),user.getAge()));
    }

八.运行结果

转载于:https://www.cnblogs.com/happygirl-zjj/p/4705772.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值