这是Player.class内部的内容
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by pietsteph on 15/09/17.
*/
public class Player implements Parcelable{
String name;
int score;
protected Player(Parcel in) {
name = in.readString();
score = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(score);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<Player> CREATOR = new Creator<Player>() {
@Override
public Player createFromParcel(Parcel in) {
return new Player(in);
}
@Override
public Player[] newArray(int size) {
return new Player[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Player(String name) {
this.name = name;
this.score = 0;
}
}
在MainActivity.class中,我将自定义对象设为size = 2(2个玩家)的数组并将其置于意图中。
Player players[] = new Player[2];
players[0] = new Player(name1);
players[1] = new Player(name2);
Intent intent = new Intent(getApplicationContext(), TurnActivity.class);
intent.putExtra(PLAYER_KEY, players);
startActivity(intent);
想要在TurnActivity.class中获得我的意图,尝试了getParcelableExtra。
Intent intent = getIntent();
Player players[] = intent.getParcelableExtra(MainActivity.PLAYER_KEY);
但它给了我一个错误
Error:(28, 59) error: incompatible types: inferred type does not conform to upper bound(s)inferred: INT#1
upper bound(s): Player[],Parcelable
where INT#1 is an intersection type:
INT#1 extends Player[],Parcelable
甚至尝试了getParcelableArrayExtra并给了我一条红线说不兼容的类型。
答案 0 :(得分:0)
实施
Parcalable
与
的界面播放器
类 我用了
Android Parcelable代码生成器插件
执行此任务。 然后,您将能够以意图保存自定义对象数组。
答案 1 :(得分:0)
这是Java 8的问题。您可能需要执行以下操作:
Intent intent = getIntent();
Parcelable parcelable[] = intent.getParcelableArrayExtra(MainActivity.PLAYER_KEY);
现在,当您使用它时,需要将其强制转换为正确的类型。像这样:
Player player = (Player)parcelable[0];
答案 2 :(得分:0)
我习惯做这样的事情
public void moveToNext(ArrayList images){
Intent mainIntent = new Intent(SplashScreen.this,MainActivity.class);
//将数据添加到parcalable
mainIntent.putParcelableArrayListExtra("data",images); startActivity(mainIntent); finish(); }
//获取数据时
ArrayList v = 。getIntent()getParcelableArrayListExtra( “数据”);