1

I have one activity 'A' which has many buttons on it to call several corresponding fragments of another activity 'B'.

Activity 'B' contains a navigation drawer where i have created fragments for all the items that we have in the navigation drawer.

So, how do i immediately launch suppose 'fragment 1' ( i.e one of the items of the navigation drawer), inside Activity B, when Activity A calls Activity B.

Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
Simran
  • 593
  • 1
  • 14
  • 37

1 Answers1

3

Add an extra to your Intent which defines which Fragment should be loaded.

intent.putExtra("fragment","FragA");

In your onCreate in Activity B:

String fragment = getIntent.getStringExtra("fragment");
// Do something to load correct fragment
Stefan
  • 2,098
  • 2
  • 18
  • 29
  • intent.putExtra("fragment","FragA"); here, what should be written in place of 'fragment' & is 'FragA' the name of the fragment that is to be loaded? – Simran Aug 30 '16 at 13:16
  • "fragment" is the key of the extra. This is used when retrieving it again. The second value, i.e. FragA is the name of your fragment. That should be set depending on the button. – Stefan Aug 30 '16 at 13:17
  • Also, String fragment = getIntent.getStringExtra("fragment"); in this statement, in onCreate where exactly do i place this statement? – Simran Aug 30 '16 at 13:17
  • Before loading the fragment, after setContentView – Stefan Aug 30 '16 at 13:18
  • Ok got it! Thanks a lot – Simran Aug 30 '16 at 13:19
  • Yes, your suggestion worked perfectly! Here, is what i wrote on button click in activity 'A': ib2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i3=new Intent(HomePageActivity.this,MainActivity.class); i3.putExtra("fragment",1); startActivity(i3); } }); – Simran Aug 30 '16 at 14:10
  • FragmentManager fm=getFragmentManager(); fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit(); int intentFragment = getIntent().getExtras().getInt("fragment"); switch (intentFragment) { case 1: fm.beginTransaction().replace(R.id.content_frame,new InventoryFragment()).commit(); break; case 2: fm.beginTransaction().replace(R.id.content_frame,new CalendarFragment()).commit(); break; } – Simran Aug 30 '16 at 14:11
  • I extended your advice by adding a switch case to check this condition for all such fragments. Thanks – Simran Aug 30 '16 at 14:12
  • Hi, i also want to pass two parameters to the fragment that i am loading, i do know how to pass extras from one activity to another but plz guide on how to pass arguments from an activity to its fragments. Thanks – Simran Sep 01 '16 at 05:51
  • http://stackoverflow.com/questions/12739909/send-data-from-activity-to-fragment-in-android – Stefan Sep 01 '16 at 06:27