Passing a Bundle on startActivity()?

后端 未结 6 1225
攒了一身酷
攒了一身酷 2020-11-22 03:28

What\'s the correct way to pass a bundle to the activity that is being launched from the current one? Shared properties?

6条回答
  •  孤街浪徒
    2020-11-22 04:11

    You have a few options:

    1) Use the Bundle from the Intent:

    Intent mIntent = new Intent(this, Example.class);
    Bundle extras = mIntent.getExtras();
    extras.putString(key, value);  
    

    2) Create a new Bundle

    Intent mIntent = new Intent(this, Example.class);
    Bundle mBundle = new Bundle();
    mBundle.putString(key, value);
    mIntent.putExtras(mBundle);
    

    3) Use the putExtra() shortcut method of the Intent

    Intent mIntent = new Intent(this, Example.class);
    mIntent.putExtra(key, value);
    


    Then, in the launched Activity, you would read them via:

    String value = getIntent().getExtras().getString(key)
    

    NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.

提交回复
热议问题