LoginSignup
18
24

More than 5 years have passed since last update.

インテントでカスタムオブジェクトを渡す

Last updated at Posted at 2013-10-02

Intentでカスタムクラスのインスタンスを渡したいときは、Parcelableインターフェイスを実装する。

//User.java


import android.os.Parcel;
import android.os.Parcelable;

public class User implements Parcelable{

    protected String mName;
    protected int mAge;
    protected List<User> mFriends;
    protected Car mCar;

    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeString(mName);
        out.writeInt(mAge);
        out.writeList(mFriends);
        out.writeParcelable(mCar);
    }

    public static final Parcelable.Creator<User> CREATOR
            = new Parcelable.Creator<User>() {
        public User createFromParcel(Parcel in) {
            return new User(in);
        }

        public User[] newArray(int size) {
            return new User[size];
        }
    };
    public User(){
        super();
    }

    private User(Parcel in) {
        mName = in.readString();
        mAge = in.readInt();
        in.readList(mFriends, User.class.getClassLoader());
        mCar = in.readParcelable(Car.class.getClassLoader());
    }

}

等としておけば、


//SomeActivity.java
User user = new User();

...
//Configure user
...

Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("user", user);
startActivity(intent);

としておいて、


//AnotherActivity.java

public void onCreate(...
...
   User user = getIntent().getParcelableExtra("user");
...

のように使える。

18
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
24