Passing enum or object through an intent (the best solution)

前端 未结 15 1007
时光取名叫无心
时光取名叫无心 2020-12-04 05:41

I have an activity that when started needs access to two different ArrayLists. Both Lists are different Objects I have created myself.

Basically I need a way to pa

15条回答
  •  不知归路
    2020-12-04 06:27

    I like simple.

    • 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;
          }
      }
      

提交回复
热议问题