zoukankan      html  css  js  c++  java
  • Activity传递参数

    1.activity之间可以通过intent传递参数。
    具体方式如下
    首先声明Intent intent = new Intetn();
    然后通过 意图跳转到另一个activity
    之后需要用到方法
    intent.putExtra(键,值);此方法和map集合一样是通过键值对 来存储数据
    startActivity(intent);


    另外一个 activity 在oncreat()方法首先要获得intent
    Bundle bundle = getIntent().getExtras();
    String msg = bundle.getString("date");
    这样就可以让基本类型传递


    2.实现Serializable接口

    这种方法也可以传递对象,但是这个对象必须实现Serializable这个接口,因为intent.putExtra()这个方法的值只能为Serializable接口的实现类。

    Student stu = new Student();
    stu.setName("你好烦");
    in.putExtra("student", stu);


    另一个activity
    Student s = (Student) bundle.get("student");

    Log.d("Activitytwo", s.getName());

    3实现Parcelable接口(安卓特有的!!)
    两种接口的区别就是Serializable是序列化到本地的
    而Parcelable是序列化到内存的,所以此种方法更快,但不能永久保存。两种方法各有优点。

    首先让要传输的对象实现Parcelable接口
    会得到两个方法

    还要写一个静态的方法
    实例化静态内部对象CREATOR实现接口Parcelable.Creator
    public static Parcelable.Creator<Student1> CREATOR = new Creator<Student1>()
    {
    //不用管
    public Student1[] newArray(int arg0)
    {
    return null;
    }
    这个方法是用来解序列化的,首先在静态的方法里要声明这个对象
    然后要解序列化的属性必须从上到下按顺序写 最后返回这个对象
    public Student1 createFromParcel(Parcel source)
    {
    Student1 s1 = new Student1();
    s1.setName(source.readString());
    s1.setAge(source.readInt());
    return s1;
    }
    };
    //不用管
    public int describeContents()
    {
    return 0;
    }
    这个方法就是用来要写序列化的方法,要把那些属性来序列化
    public void writeToParcel(Parcel p, int arg1)
    {
    p.writeString(name);
    p.writeInt(age);
    }

    public interface Parcelable
    {
    //内容描述接口,基本不用管
    public int describeContents();
    //写入接口函数,打包
    public void writeToParcel(Parcel dest, int flags);
    //读取接口,目的是要从Parcel中构造一个实现了Parcelable的类的实例处理。因为实现类在这里还是不可知的,所以需要用到模板的方式,继承类名通过模板参数传入
    //为了能够实现模板参数的传入,这里定义Creator嵌入接口,内含两个接口函数分别返回单个和多个继承类实例
    public interface Creator<T>
    {
    public T createFromParcel(Parcel source);
    public T[] newArray(int size);
    }
    }

  • 相关阅读:
    装饰器
    kolla部署all-in-one
    k8s集群部署gitlab
    helm部署gitlab
    控制器和pod调度流程
    esxi安装
    Linux系统性能分析工具
    configMap和secret
    etcd 问题、调优、监控
    动感单车
  • 原文地址:https://www.cnblogs.com/84126858jmz/p/4869627.html
Copyright © 2011-2022 走看看