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()));
    }

八.运行结果

posted @ 2015-08-05 20:27  Rosanne  阅读(630)  评论(0编辑  收藏  举报