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

    八.运行结果

  • 相关阅读:
    Hibernate 5.x 生成 SessionFactory 源码跟踪分析
    编译iftop
    Too many open files
    ffmpeg指定网卡
    abrt-hook-ccpp使用CPU太多
    ffplay播放时显示信息的意义
    Windows换行符和Linux换行符的替换
    directshow在WIN10下的一个BUG
    使用mirrordriver截屏
    mac xmind 激活
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4705772.html
Copyright © 2020-2023  润新知