I have a MainActivity that has several fragments which are added and then shown/hidden. This is because the MainActivity uses a NavigationDrawer
. Clicking on items in the drawer causes different fragments to be added (if they do not exist), or shown/hidden if they do.
My question is, how can I launch my MainActivity via an intent from a different activity, and at the same time show a specific fragment?
Would I have to pass some extra to my MainActivity and then based on that data, add/show/hide the relevant fragment? Is there another way?
Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.
Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.
When you create your Intent, you can give it an extra that determines the fragment to load.
Intent i = new Intent(this, ActivityClass.class);
i.putExtra("frgToLoad", FRAGMENT_A);
// Now start your activity
startActivity(i);
Now, inside your activity check the extra and load the right Fragment:
OnCreate(){
...
int intentFragment = getIntent().getExtras().getInt("frgToLoad");
switch (intentFragment){
case FRAGMENT_A:
// Load corresponding fragment
break;
case FRAGMENT_B:
// Load corresponding fragment
break;
case FRAGMENT_C:
// Load corresponding fragment
break;
}
}
You can use sharedPreference to achieve the goals. Save the index after you open you TAB/Fragment.
//get current tab
sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
String position = sharedPreferences.getString("tab_opened", null);
if(position==null){
viewPager.setCurrentItem(1,true);
}else if(position=="0"){
viewPager.setCurrentItem(0,true);
}else if(position=="1"){
viewPager.setCurrentItem(1,true);
}else if(position=="2"){
viewPager.setCurrentItem(2,true);
}
}// <<<~~~ THAT IS END OF onCreate() method.
Please refer to this tutorial : OPEN THIS .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With