내 물건을 Parcelable로 만들려고합니다. 그러나 사용자 정의 객체가 있으며 해당 객체에는 ArrayList
내가 만든 다른 사용자 정의 객체의 속성이 있습니다.
가장 좋은 방법은 무엇입니까?
답변
여기 , 여기 (코드는 여기에 있습니다) 및 여기에 몇 가지 예가 있습니다 .
이를 위해 POJO 클래스를 만들 수 있지만 추가 코드를 추가해야합니다 Parcelable
. 구현을 살펴보십시오.
public class Student implements Parcelable{
private String id;
private String name;
private String grade;
// Constructor
public Student(String id, String name, String grade){
this.id = id;
this.name = name;
this.grade = grade;
}
// Getter and setter methods
.........
.........
// Parcelling part
public Student(Parcel in){
String[] data = new String[3];
in.readStringArray(data);
// the order needs to be the same as in writeToParcel() method
this.id = data[0];
this.name = data[1];
this.grade = data[2];
}
@Оverride
public int describeContents(){
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.id,
this.name,
this.grade});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Student createFromParcel(Parcel in) {
return new Student(in);
}
public Student[] newArray(int size) {
return new Student[size];
}
};
}
이 클래스를 작성하면이 클래스의 오브젝트를 이와 Intent
같이 쉽게 전달 하고 대상 활동에서이 오브젝트를 복구 할 수 있습니다.
intent.putExtra("student", new Student("1","Mike","6"));
여기에서 학생은 번들에서 데이터를 추출하는 데 필요한 키입니다.
Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");
이 예는 String
유형 만 보여줍니다 . 그러나 원하는 모든 종류의 데이터를 소포로 묶을 수 있습니다. 사용해보십시오.
편집 : Rukmal Dias가 제안한 또 다른 예 .
답변
답변
IntelliJ IDEA 및 Android Studio에는이를위한 플러그인이 있습니다.
- ★ 안드로이드 Parcelable 코드 생성기 (Apache License 2.0)
- 자동 소포 (MIT 라이센스 )
- SerializableParcelable Generator (MIT 라이센스 )
- 소포 가능 코드 생성기 (Kotlin 용) (Apache License 2.0)
이 플러그인 은 클래스의 필드를 기반으로 Android Parcelable 상용구 코드를 생성 합니다.
답변
1. 수입 Android Parcelable code generator
2. 수업 만들기
public class Sample {
int id;
String name;
}
3. 메뉴에서 생성> 소포 가능
끝난.
답변
어떻게? 주석으로.
당신은 단순히 특별한 주석으로 POJO에 주석을 달고 라이브러리는 나머지를 수행합니다.
경고!
Hrisey, Lombok 및 기타 코드 생성 라이브러리가 Android의 새로운 빌드 시스템과 호환되는지 확실하지 않습니다. 핫 스와핑 코드 (예 : jRebel, Instant Run)로 훌륭하게 재생되거나 재생되지 않을 수 있습니다.
장점 :
- 코드 생성 라이브러리는 상용구 소스 코드에서 저장됩니다.
- 주석은 수업을 아름답게 만듭니다.
단점 :
- 간단한 수업에 적합합니다. 복잡한 클래스를 소포로 만드는 것은 까다로울 수 있습니다.
- 롬복과 AspectJ는 잘 어울리지 않습니다. [세부]
- 내 경고를 참조하십시오.
Hrisey
경고!
Hrisey는 Java 8과 관련하여 알려진 문제가 있으므로 현재 Android 개발에 사용할 수 없습니다. # 1 심볼 오류를 찾을 수 없음 (JDK 8)을 참조하십시오 .
Hrisey는 Lombok을 기반으로 합니다. Hrisey를 사용한 소포 가능 클래스 :
@hrisey.Parcelable
public final class POJOClass implements android.os.Parcelable {
/* Fields, accessors, default constructor */
}
이제 Parcelable 인터페이스의 메소드를 구현할 필요가 없습니다. Hrisey는 전처리 단계에서 필요한 모든 코드를 생성합니다.
Gradle 종속성의 Hrisey :
provided "pl.mg6.hrisey:hrisey:${hrisey.version}"
지원되는 유형 은 여기 를 참조하십시오 . 는 ArrayList
그들 중 하나입니다.
IDE 용 플러그인 Hrisey xor Lombok *를 설치하고 놀라운 기능을 사용하십시오!
* Hrisey 및 Lombok 플러그인을 함께 활성화하지 마십시오. IDE 실행 중에 오류가 발생합니다.
소포
Parceler를 사용한 소포 가능 클래스 :
@java.org.parceler.Parcel
public class POJOClass {
/* Fields, accessors, default constructor */
}
생성 된 코드를 사용하려면 생성 된 클래스를 직접 참조하거나 Parcels
유틸리티 클래스를 통해
public static <T> Parcelable wrap(T input);
의 참조를 @Parcel
취소하려면 다음 Parcels
클래스의 메소드를 호출하십시오.
public static <T> T unwrap(Parcelable input);
Gradle 종속성의 Parceler :
compile "org.parceler:parceler-api:${parceler.version}"
provided "org.parceler:parceler:${parceler.version}"
지원되는 속성 유형 은 README 를 참조하십시오 .
자동 소포
AutoParcel 은 Parcelable Values 생성을 가능하게 하는 AutoValue 확장입니다.
주석이 달린 모델에 추가 implements Parcelable
하십시오 @AutoValue
.
@AutoValue
abstract class POJOClass implements Parcelable {
/* Note that the class is abstract */
/* Abstract fields, abstract accessors */
static POJOClass create(/*abstract fields*/) {
return new AutoValue_POJOClass(/*abstract fields*/);
}
}
Gradle 빌드 파일의 AutoParcel :
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
repositories {
/*...*/
maven {url "https://clojars.org/repo/"}
}
dependencies {
apt "frankiesardo:auto-parcel:${autoparcel.version}"
}
종이 소포
PaperParcel 은 Kotlin 및 Java에 대해 형식이 안전한 Parcelable 상용구 코드를 자동으로 생성하는 주석 프로세서입니다. PaperParcel은 Kotlin Data Classes, AutoValue Extension을 통한 Google의 AutoValue 또는 일반 Java Bean 객체를 지원합니다.
에서 사용 예 문서 .
로 데이터 클래스에 주석을 달고 @PaperParcel
구현 PaperParcelable
하고 다음과 같은 JVM 정적 인스턴스를 추가하십시오 PaperParcelable.Creator
.
@PaperParcel
public final class Example extends PaperParcelable {
public static final PaperParcelable.Creator<Example> CREATOR = new PaperParcelable.Creator<>(Example.class);
private final int test;
public Example(int test) {
this.test = test;
}
public int getTest() {
return test;
}
}
Kotlin 사용자의 경우 Kotlin 사용을 참조하십시오 . AutoValue 사용자의 경우 AutoValue 사용을 참조하십시오 .
ParcelableGenerator
ParcelableGenerator (README는 중국어로 작성되었으며 이해가되지 않습니다. 영어-중국어를 사용하는 개발자가이 답변에 기여한 것을 환영합니다)
에서 사용 예 README .
import com.baoyz.pg.Parcelable;
@Parcelable
public class User {
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;
}
}
안드로이드-APT 안드로이드 스튜디오와 함께 주석 프로세서 작업에서 플러그인 도움을줍니다.
답변
답변
안드로이드 스튜디오에서 플러그인을 사용하여 객체를 Parcelables로 만들 수 있습니다.
public class Persona implements Parcelable {
String nombre;
int edad;
Date fechaNacimiento;
public Persona(String nombre, int edad, Date fechaNacimiento) {
this.nombre = nombre;
this.edad = edad;
this.fechaNacimiento = fechaNacimiento;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.nombre);
dest.writeInt(this.edad);
dest.writeLong(fechaNacimiento != null ? fechaNacimiento.getTime() : -1);
}
protected Persona(Parcel in) {
this.nombre = in.readString();
this.edad = in.readInt();
long tmpFechaNacimiento = in.readLong();
this.fechaNacimiento = tmpFechaNacimiento == -1 ? null : new Date(tmpFechaNacimiento);
}
public static final Parcelable.Creator<Persona> CREATOR = new Parcelable.Creator<Persona>() {
public Persona createFromParcel(Parcel source) {
return new Persona(source);
}
public Persona[] newArray(int size) {
return new Persona[size];
}
};}