Android: How to put an Enum in a Bundle?

前端 未结 12 1414
别那么骄傲
别那么骄傲 2020-12-22 16:56

How do you add an Enum object to an Android Bundle?

相关标签:
12条回答
  • 2020-12-22 17:23

    Use bundle.putSerializable(String key, Serializable s) and bundle.getSerializable(String key):

    enum Mode = {
      BASIC, ADVANCED
    }
    
    Mode m = Mode.BASIC;
    
    bundle.putSerializable("mode", m);
    
    ...
    
    Mode m;
    m = bundle.getSerializable("mode");
    

    Documentation: http://developer.android.com/reference/android/os/Bundle.html

    0 讨论(0)
  • 2020-12-22 17:28

    I use kotlin.

    companion object {
    
            enum class Mode {
                MODE_REFERENCE,
                MODE_DOWNLOAD
            }
    }
    

    then put into Intent:

    intent.putExtra(KEY_MODE, Mode.MODE_DOWNLOAD.name)
    

    when you net to get value:

    mode = Mode.valueOf(intent.getStringExtra(KEY_MODE))
    
    0 讨论(0)
  • 2020-12-22 17:31

    For Intent you can use this way:

    Intent : kotlin

    FirstActivity :

    val intent = Intent(context, SecondActivity::class.java)
    intent.putExtra("type", typeEnum.A)
    startActivity(intent)
    

    SecondActivity:

    override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState) 
         //...
         val type = (intent.extras?.get("type") as? typeEnum.Type?)
    }
    
    0 讨论(0)
  • 2020-12-22 17:32

    Enums are Serializable so there is no issue.

    Given the following enum:

    enum YourEnum {
      TYPE1,
      TYPE2
    }
    

    Bundle:

    // put
    bundle.putSerializable("key", YourEnum.TYPE1);
    
    // get 
    YourEnum yourenum = (YourEnum) bundle.get("key");
    

    Intent:

    // put
    intent.putExtra("key", yourEnum);
    
    // get
    yourEnum = (YourEnum) intent.getSerializableExtra("key");
    
    0 讨论(0)
  • 2020-12-22 17:32

    It may be better to pass it as string from myEnumValue.name() and restore it from YourEnums.valueOf(s), as otherwise the enum's ordering must be preserved!

    Longer explanation: Convert from enum ordinal to enum type

    0 讨论(0)
  • 2020-12-22 17:39

    I've created a Koltin extension:

    fun Bundle.putEnum(key: String, enum: Enum<*>) {
        this.putString( key , enum.name )
    }
    
    inline fun <reified T: Enum<T>> Intent.getEnumExtra(key:String) : T {
        return enumValueOf( getStringExtra(key) )
    }
    
    

    Create a bundle and add:

    Bundle().also {
       it.putEnum( "KEY" , ENUM_CLAS.ITEM )
    }
    
    

    and get:

    intent?.getEnumExtra< ENUM_CLAS >( "KEY" )?.let{}
    
    
    0 讨论(0)
提交回复
热议问题