我有一个活动,启动时需要访问两个不同的数组列表。两个列表都是我自己创建的不同对象。

基本上,我需要一种方法来将这些对象从Intent传递给活动。我可以使用addExtras(),但这需要一个Parceable兼容类。我可以使我的类传递序列化,但据我所知,这减慢了程序。

我有什么选择?

我可以传递一个Enum吗?

题外话:有没有一种方法可以将参数从Intent传递给Activity构造函数?


当前回答

考虑以下enum::

public static  enum MyEnum {
    ValueA,
    ValueB
}

对于通过::

 Intent mainIntent = new Intent(this,MyActivity.class);
 mainIntent.putExtra("ENUM_CONST", MyEnum.ValueA);
 this.startActivity(mainIntent);

从intent/bundle/arguments中返回:

 MyEnum myEnum = (MyEnum) intent.getSerializableExtra("ENUM_CONST");

其他回答

不要使用枚举。不使用枚举的第78个理由。:)使用整数,可以通过Bundle和Parcelable轻松远程。

我认为最好的办法是将这些列表转换为一些可打包的东西,如字符串(或映射?),以将其传递给活动。然后Activity将不得不将其转换回数组。

实现自定义包装是一个痛苦的脖子,所以我将尽可能避免它。

我喜欢简单。

The Fred activity has two modes -- HAPPY and SAD. Create a static IntentFactory that creates your Intent for you. Pass it the Mode you want. The IntentFactory uses the name of the Mode class as the name of the extra. The IntentFactory converts the Mode to a String using name() Upon entry into onCreate use this info to convert back to a Mode. You could use ordinal() and Mode.values() as well. I like strings because I can see them in the debugger. public class Fred extends Activity { public static enum Mode { HAPPY, SAD, ; } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.betting); Intent intent = getIntent(); Mode mode = Mode.valueOf(getIntent().getStringExtra(Mode.class.getName())); Toast.makeText(this, "mode="+mode.toString(), Toast.LENGTH_LONG).show(); } public static Intent IntentFactory(Context context, Mode mode){ Intent intent = new Intent(); intent.setClass(context,Fred.class); intent.putExtra(Mode.class.getName(),mode.name()); return intent; } }

您可以将枚举作为字符串传递。

public enum CountType {
    ONE,
    TWO,
    THREE
}

private CountType count;
count = ONE;

String countString = count.name();

CountType countToo = CountType.valueOf(countString);

给定字符串的支持,你应该能够传递枚举的值没有问题。

考虑以下enum::

public static  enum MyEnum {
    ValueA,
    ValueB
}

对于通过::

 Intent mainIntent = new Intent(this,MyActivity.class);
 mainIntent.putExtra("ENUM_CONST", MyEnum.ValueA);
 this.startActivity(mainIntent);

从intent/bundle/arguments中返回:

 MyEnum myEnum = (MyEnum) intent.getSerializableExtra("ENUM_CONST");