ArrayList
Parcelable
활동에 사용자 정의 객체 목록을 전달하기 위해 를 만들려고 합니다. 나는 myObjectList
확장 ArrayList<myObject>
하고 구현 하는 클래스를 작성하기 시작 합니다 Parcelable
.
의 일부 속성 MyObject
은 boolean
있지만 Parcel
메소드가 없습니다 read/writeBoolean
.
이것을 처리하는 가장 좋은 방법은 무엇입니까?
답변
내가하는 방법은 다음과 같습니다.
writeToParcel :
dest.writeByte((byte) (myBoolean ? 1 : 0)); //if myBoolean == true, byte == 1
readFromParcel :
myBoolean = in.readByte() != 0; //myBoolean == true if byte != 0
답변
writeValue 메소드를 사용할 수도 있습니다 . 제 생각에는 이것이 가장 간단한 해결책입니다.
dst.writeValue( myBool );
그런 다음 간단한 캐스트로 쉽게 검색 할 수 있습니다 Boolean
.
boolean myBool = (Boolean) source.readValue( null );
후드 아래에서 Android Framework는 정수로 처리합니다.
writeInt( (Boolean) v ? 1 : 0 );
답변
당신은 이렇게 선언합니다
private boolean isSelectionRight;
쓰다
out.writeInt(isSelectionRight ? 1 : 0);
읽다
isSelectionRight = (in.readInt() == 0) ? false : true;
부울 형식은 Parcel이 지원하는 형식으로 변환해야하므로 int로 변환 할 수 있습니다.
답변
클래스에서 Parcelable을 구현 한 후 AndroidStudio (2.3 atm 사용)를 사용하면 클래스 이름 위에 마우스 포인터를 놓으면 Parcelable 구현을 추가하라는 메시지가 표시됩니다.
네 개의 필드에서 다음을 생성합니다.
public class YourClass implements Parcelable{
String someString;
int someInt;
boolean someBoolean;
List<String> someList;
protected YourClass(Parcel in) {
someString = in.readString();
someInt = in.readInt();
someBoolean = in.readByte() != 0;
someList = in.createStringArrayList();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(someString);
dest.writeInt(someInt);
dest.writeByte((byte) (someBoolean ? 1 : 0));
dest.writeStringList(someList);
}
...
답변
나는 보통 그것들을 배열로 가지고 writeBooleanArray
있고readBooleanArray
포장해야하는 단일 부울 인 경우 다음을 수행 할 수 있습니다.
parcel.writeBooleanArray(new boolean[] {myBool});
답변
out.writeInt(mBool ? 1 : 0); //Write
this.mBool =in.readInt()==1; //Read
답변
Android Studio를 사용하는 경우 Parcelable을 구현하는 가장 쉬운 방법을 제안했습니다.
파일-> 설정-> 플러그인-> 리포지토리 찾아보기 로 이동하여 소포를 검색하십시오.
그리고 이것을하기위한 웹리스트도 있습니다. http://www.parcelabler.com/