将对象列表传递给PagerActivity

时间:2015-04-15 08:21:25

标签: android android-activity android-pageradapter

我有一个列表,其中包含从列表中获取的文章,并希望在PagerActivity中显示所选文章,以便用户可以在完成阅读之前和之后轻松翻阅文章。

在iOS中,我可以将带有文章对象的List(或引用)传递给PagerActivity。但是在Android中,调用Intent不允许传递列表。那么最好的方法是什么呢?我是否需要在下一个Activity中重新加载数组,然后将该位置作为参数传递给Intent?

(重新加载列表会很昂贵,但如果自加载后数据库没有更改,则应该有效,否则订单可能会有所不同,可能会显示错误的项目。)

2 个答案:

答案 0 :(得分:1)

在Android中

如果您拥有ParecleObject,则使用Custom Object ArrayList,如果您拥有简单String ArrayList,则直接通过意图

如果您有简单String ArrayList,请参阅下面的

Passing ArrayList of string arrays from one activity to another in android

如果您有Custom Object ArrayList,请参阅下面的

How to pass ArrayList<CustomeObject> from one activity to another?

Passing arraylist of objects between activities

答案 1 :(得分:1)

在此处考虑您的类型列表:

public class Department implements Parcelable {
    int department_id;
    String title;

    public Department() {
        this.department_id = 0;
        this.title = null;
    }

    public Department(int department_id, String title) {
        this.department_id = department_id;
        this.title = title;
    }

    public int getDepartmentId() {
        return department_id;
    }

    public void setDepartmentId(int department_id) {
        this.department_id = department_id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

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

    @Override
    public void writeToParcel(Parcel parcel, int flag) {
        parcel.writeInt(department_id);
        parcel.writeString(title);
    }

    public static final Creator<Department> CREATOR = new Creator<Department>(){

        @Override
        public Department createFromParcel(Parcel parcel) {
            Department department = new Department();
            department.setDepartmentId(parcel.readInt());
            department.setTitle(parcel.readString());
            return department;
        }

        @Override
        public Department[] newArray(int size) {

            return new Department[size];
        }

    };
}

List<Department> departments = new ArrayList<>();

现在你只需将此列表放在Intent Bundle中就像这样

bundle.putParcelableArrayList("Departments_KEY", departments);

并接收您孩子活动中的列表

List<Department> departments = getIntent() or getArguments().getParcelable("Departments_KEY");