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

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

我有什么选择?

我可以传递一个Enum吗?

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


当前回答

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

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

其他回答

它可以使你的Enum实现Serializable,然后你可以通过Intent传递它,因为有一个方法可以将它作为一个Serializable传递。使用int而不是enum的建议是错误的。枚举用于使代码更易于阅读和维护。如果不能使用枚举,这将是倒退到黑暗时代的一大步。

大多数使用Parcelable概念的答案都是在Java代码中。在Kotlin中更容易做到这一点。

只需用@Parcelize注释枚举类并实现Parcelable接口。

@Parcelize
enum class ViewTypes : Parcelable {
TITLE, PRICES, COLORS, SIZES
}

如果你只是想发送一个枚举,你可以这样做:

首先声明一个包含一些值的枚举(可以通过intent传递):

 public enum MyEnum {
    ENUM_ZERO(0),
    ENUM_ONE(1),
    ENUM_TWO(2),
    ENUM_THREE(3);
    private int intValue;

    MyEnum(int intValue) {
        this.intValue = intValue;
    }

    public int getIntValue() {
        return intValue;
    }

    public static MyEnum getEnumByValue(int intValue) {
        switch (intValue) {
            case 0:
                return ENUM_ZERO;
            case 1:
                return ENUM_ONE;
            case 2:
                return ENUM_TWO;
            case 3:
                return ENUM_THREE;
            default:
                return null;
        }
    }
}

然后:

  intent.putExtra("EnumValue", MyEnum.ENUM_THREE.getIntValue());

当你想要得到它时:

  NotificationController.MyEnum myEnum = NotificationController.MyEnum.getEnumByValue(intent.getIntExtra("EnumValue",-1);

小菜一碟!

我认为最好的办法是将这些列表转换为一些可打包的东西,如字符串(或映射?),以将其传递给活动。然后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; } }