Android控件使用篇Android专题Android

Intent传递列表对象数据用法解析:数据序列化

2020-12-08  本文已影响0人  千夜零一

Intent如何传递List?

答:需要首先将要传递的对象实体类进行序列化。再通过Intent、Bundle对象传递给其他Activity。
Why? 不同 Activity 之间传输数据可以通过 Intent 对象的 putExtra 方法传递,对于 java 的八大基本数据类型(char int float double long short boolean byte)传递是没有问题的,但是如果传递比较复杂的对象类型(比如对象,比如集合等),那么就可能存在问题,就需要实现数据对象的数据序列化, 将这些对象放到一个 Intent 或者 Bundle 里面,然后再传递。


如何对实体类进行序列化?

  Android中实现序列化有两种机制(实现Serializable接口/实现parcelable接口),我们采用第二种机制:实现parcelable接口

  1. 打开AndroidStudio的设置界面,搜索Parcelable安装序列化插件
  2. 对对象实体类进行改造:需要实现Parcelable接口(此时提示需要重写几个方法,不用管,采用插件进行第三步处理自动重写)
  3. 右键选择Parcelable插件,一键重写方法,得到:用法中的步骤四。

效果预览


用法

步骤一、创建ActivityA的布局文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".blog2.Case68"
    tools:ignore="MissingConstraints">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="@color/black"
        android:gravity="center"
        android:text="Activity_A"
        android:textColor="@color/white"
        android:textSize="20sp" />

    <Button
        android:id="@+id/btnGo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转页面传值"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:padding="15dp"
        android:textSize="20sp" />

</androidx.constraintlayout.widget.ConstraintLayout>

步骤二、创建实体类:Movie

/**
 * @data on 12/2/20 9:33 AM
 * @auther armStrong
 * @describe 电影实体类
 */
public class Movie{
    private int id;
    private String name;
    private String record; //票房记录

    public Movie() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRecord() {
        return record;
    }

    public void setRecord(String record) {
        this.record = record;
    }

    public Movie(int id, String name, String record) {
        this.id = id;
        this.name = name;
        this.record = record;
    }
}

步骤三、在ActivityA中书写业务逻辑代码

public class Case68 extends AppCompatActivity {
    private Button btnA;
    //定义一个ArrayList并且跳转时传递它
    private ArrayList movieList = new ArrayList<Movie> ();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_case68);
        initView();
        initList();
        btnA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToB();
            }
        });
    }

    private void initView() {
        btnA = findViewById(R.id.btnGo);
    }

    private void goToB(){
        Intent intent = new Intent();
        intent.putExtra("key1", "可可托海的牧羊人");
        intent.putParcelableArrayListExtra("key2",movieList);
        intent.setClass(this, Case68Other.class);
        startActivity(intent);
        finish();
    }

    private void initList(){
        movieList.add(new Movie(1,"《金刚川》","100万"));
        movieList.add(new Movie(2,"《疯狂原始人》","200万"));
        movieList.add(new Movie(3,"《一秒钟》","300万"));
        movieList.add(new Movie(4,"《除暴》","400万"));
    }
}

步骤四、对实体类Movie进行序列化(对比第二步)

/**
 * @data on 12/2/20 9:33 AM
 * @auther armStrong
 * @describe 电影实体类——序列化
 */
public class Movie implements Parcelable {
    private int id;
    private String name;
    private String record; //票房记录

    public Movie() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRecord() {
        return record;
    }

    public void setRecord(String record) {
        this.record = record;
    }

    public Movie(int id, String name, String record) {
        this.id = id;
        this.name = name;
        this.record = record;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.id);
        dest.writeString(this.name);
        dest.writeString(this.record);
    }

    protected Movie(Parcel in) {
        this.id = in.readInt();
        this.name = in.readString();
        this.record = in.readString();
    }

    public static final Creator<Movie> CREATOR = new Creator<Movie>() {
        @Override
        public Movie createFromParcel(Parcel source) {
            return new Movie(source);
        }

        @Override
        public Movie[] newArray(int size) {
            return new Movie[size];
        }
    };
}

步骤五、创建ActivityB的布局文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.Case68Other"
    android:background="@color/gray"
    tools:ignore="MissingConstraints">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="@color/black"
        android:gravity="center"
        android:text="Activity_B"
        android:textColor="@color/white"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/showTvStr"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:gravity="center"
        android:textSize="18sp"
        android:background="@color/white"
        android:text="输出字符串"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/divider"
        android:layout_width="0dp"
        android:layout_marginHorizontal="10dp"
        android:layout_height="1dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:background="@color/black"
        app:layout_constraintTop_toBottomOf="@id/showTvStr" />

    <TextView
        android:id="@+id/showTvList"
        android:background="@color/white"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:gravity="center"
        android:textSize="18sp"
        android:text="输出列表数据"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/divider" />

</androidx.constraintlayout.widget.ConstraintLayout>

步骤六、在ActivityB中书写业务逻辑代码

public class Case68Other extends AppCompatActivity {
    private TextView tvShowStr;
    private TextView tvShowList;

    private String str;
    private ArrayList<Movie> mList = new ArrayList<Movie> ();;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_case68_other);
        initView();
        getParameter();
        showText();
    }

    private void initView() {
        tvShowStr = findViewById(R.id.showTvStr);
        tvShowList = findViewById(R.id.showTvList);
    }

    private void getParameter(){
        str = getIntent().getStringExtra("key1");
        mList = getIntent().getParcelableArrayListExtra("key2");
    }

    private void showText(){
        tvShowStr.setText(str);
        StringBuilder stringBuilder = new StringBuilder();
        for (Movie m : mList){
            stringBuilder.append("Id:"+m.getId()+";"+"Name:"+m.getName()+";"+"Record:"+m.getRecord()+"."+"\n");
        }
        tvShowList.setText(stringBuilder);
    }
}

大功告成!

上一篇下一篇

猜你喜欢

热点阅读