Question newcomer to android. I started to study intents: I want to attach 3 buttons to 3 layout, so that in the second activit we could see which button was pressed and the corresponding layout was called. So generally do? And how to do it correctly through intent?

Activity_1.java:

public void onClick(View v){ switch (v.getId()){ case R.id.button_1: { Intent intent = new Intent (getApplicationContext(),Activity_2.class); intent.putExtra("key","b1"); startActivity(intent); break; } case R.id.button_2: { Intent intent = new Intent (getApplicationContext(),Activity_2.class); intent.putExtra("key","b2"); startActivity(intent); break; } case R.id.button_3: { Intent intent = new Intent (getApplicationContext(),Activity_2.class); intent.putExtra("key","b3"); startActivity(intent); break; } 

Activity_2.java:

 @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate (savedInstanceState); String data = getIntent().getStringExtra("key"); if (data == "b1") setContentView (R.layout.activity_number1); else if (data == "b2") setContentView (R.layout.activity_number2); else setContentView (R.layout.activity_number3); } 
  • one
    Before continuing, you should read this answer and think well again - pavlofff
  • @pavlofff thanks for the link. I understand correctly that such a solution is not used in actual practice? Those. if a lot of layout, it is better to implement through fragments? - Mr_FFFFFF
  • You can try, but very soon you will understand that it is not just not used, but absolutely not working, if you are planning to interact with the interface. - pavlofff
  • @pavlofff I want to do it right away. In this particular case, will it be correct to create 3 Activities for each markup? - Mr_FFFFFF
  • If each screen displays different widgets (different screen layouts), then yes: 3 activations or 1 activations with 3 fragments - pavlofff

1 answer 1

In general, everything is correct. But you can simplify the code.

Add a static start(String key) method to Activity_2.java . It starts Activity_2 with the key addition (writes the key string argument to the intent).

 public static void start(Context context, String key) { Intent starter = new Intent(context, Activity_2.class); starter.putExtra("KEY", key); context.startActivity(starter); } 

And in Activity_1.java will look like this:

 public void onClick(View v){ switch (v.getId()){ case R.id.button_1: { Activity_2.start(Activity_1.this, "b1"); break; } case R.id.button_2: { Activity_2.start(Activity_1.this, "b2"); break; } case R.id.button_3: { Activity_2.start(Activity_1.this, "b3"); break; } 
  • I can not understand why it is called only (R.layout.activity_number3)? - Mr_FFFFFF
  • @Mr_FFFFFF, How to compare strings in Java? - woesss
  • @woesss thanks) - Mr_FFFFFF