【发布时间】:2013-04-11 09:41:00
【问题描述】:
我正在尝试通过为我玩的棋盘游戏制作一个帮助程序来学习 Android 开发。我遇到的情况与Pass custom object between activities 中回答的情况非常相似。我的情况不同的是,有问题的自定义对象都在扩展一个抽象类。
抽象类代表一个筹码(类似于纸牌游戏),如下:
import java.util.ArrayList;
public abstract class Chip{
protected String name;
protected int imageID;
protected ArrayList<String> chipColors;
protected ArrayList<String> chipTypes;
public String toString(){
return name;
}
//Getters
public String getName(){ return name; }
public int getImageID() { return imageID; }
public String getSet() { return set; }
//Figure out how I need to deal with colors/types when I get there
}
一个可以扩展 Chip 的类的例子:
public class ChipA extends Chip{
public ChipA (){
super();
name = "Chip A";
imageID = R.drawable.chipa;
set = "Basic";
chipTypes = new ArrayList<String>();
chipTypes.add("typeA");
chipColors = new ArrayList<String>();
chipColors.add("red");
chipColors.add("green");
}
}
我采用这种方法是为了创建合适类型的新芯片,只需在需要的地方调用new ChipA(),而不是new Chip(<long list of arguments that describe Chip A>)。我需要将这些筹码的集合从一个活动传递到另一个活动。我已经在我的代码中解决了这个问题,方法是按照this article 中的描述存储我想要在全球范围内传递的芯片,但是文章的结尾建议使用intent extras 来代替这种操作。有人可以更清楚地解释为什么吗?这只是约定吗?如果只是可读性的问题,这个方法看起来比较简洁易读。
通过阅读,很明显,使用 Intent extra 在活动之间传递任意类的预期方法是让它们实现 Parcelable。但是,由于我正在处理相关类的许多子类,这意味着将writeToParcel 和Parcelable.Creator 添加到每个子类。 (describeContents() 似乎并不重要,据我了解,我可以在基本抽象类中实现它。)我可能会在这里有很多子类,这意味着添加大量重复代码。在这种情况下,实施Parcelable 是否仍被视为首选方法?我是否遗漏了一些可以让我减少冗余代码的东西?如果可能的话,我宁愿保持我的 Chip 子类相当紧凑。
请轻点,我是 Stack Overflow 和 Android 开发的新手。
【问题讨论】:
标签: java android oop android-intent android-activity