首页 > 其他 > 详细

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

时间:2015-08-05 22:04:15      阅读:225      评论:0      收藏:0      [点我收藏+]

一.新建一个空的工程

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

技术分享

三.新建一个空的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()));
    }

八.运行结果

技术分享技术分享

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

原文:http://www.cnblogs.com/happygirl-zjj/p/4705772.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!