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?
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 .
In case you are looking for something like this, hope so!
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment;
FragmentManager fManager = getFragmentManager();
Bundle args = new Bundle();
args.putInt(MCConstants.ARG_SECTION_NUMBER, position);
clearAllBackStack();
FragmentTransaction fTransaction = fManager.beginTransaction();
switch (position) {
case 0:
fragment = new FirstFragment();
fragment.setArguments(args);
fTransaction.replace(R.id.container, fragment,
"FTAG").commit();
break;
case 1:
fragment = new SecFragment();
fragment.setArguments(args);
fTransaction.replace(R.id.container, fragment,
"STAG").commit();
break;
case 2:
fragment = new ThirdFragment();
fragment.setArguments(args);
fTransaction.replace(R.id.container, fragment,
"TTAG").commit();
break;
}
}
Related
I have implemented a navigation drawer in my application, The application is a tabbed layout and I think this is where the problem is coming from.
AT the moment I have a listener on the items in the Nav drawer to launch a new fragment when pressed. The issue is that when I press one of the items the fragment doesnt seem to load and the current fragment just goes blank.
How do I set the layout of the fragment to launch once the item has been selected? As my current method doesnt seem to be working. The below shows my current attemp where R.id.viewpager is what I am trying to replace. Is there a way of just launching the fragments layout and completely replacing the layout with the new fragments layout?
onDrawerItemSelected
#Override
public void onDrawerItemSelected(View view, int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position)
{
case 0:
{
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
case 1:
fragment = new FavouritesFragment();
title = getString(R.string.title_favourites);
break;
case 2:
fragment = new HelpFragment();
title = getString(R.string.title_help);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.viewpager, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
fragmentTransaction.replace(R.id.viewpager, fragment);
You don't replace the viewpager, you set current item for the viewPager. You should have a PagerAdapter that defines which fragment to show for the position.
okay i know there are other questions that on first glance make this one look like a duplicate, but none of these answers work in my case,
What i want is the first fragment displayed to be like a Main Activity in respect to how the back button works, i need whichever fragment i choose from my navigation drawer to go back to the first fragment when the back button is pressed then a user would quit the app by pressing it again.
So ive tried using addToBackStack and when i move to another fragment if i press the back button it comes back to my first fragment (exactly as i want) but pressing the back button again leaves me with a white screen (i wonder if this is due to the transaction animation im using which ive included below) so to get around this i tried overriding the back button and throwing in a call to finish(); but this causes whichever fragment im in to finish instead of going back to the first fragment, ive tried a handful of workarounds from the above mentioned link and many others but cannot find a decent fix any suggestions?
here is my Main Activity displayView
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new glideFrag();
break;
case 2:
fragment = new secondGlideFrag();
break;
case 3:
fragment = new thirdGlideFrag();
break;
case 4:
fragment = new forthGlideFrag();
break;
case 5:
fragment = new lgFrag();
break;
case 6:
fragment = new cyanFrag();
break;
case 7:
fragment = new sonyFrag();
break;
case 8:
fragment = new SecondFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter,R.anim.pop_exit);
//fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.frame_container, fragment).addToBackStack("first Fragment").commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
i found this that looks like a great way around it
private boolean popNext = false;
if(popNext){
if(position == INITIAL_POSITION){
onBackPressed();
mDrawerLayout.closeDrawer(mDrawerList);
popNext = false;
return;
}
getSupportFragmentManager().popBackStackImmediate();
}
else{
if(position == INITIAL_POSITION){
mDrawerLayout.closeDrawer(mDrawerList);
return;
}
popNext=true;
}
but im still fairly new to android and im not sure what to set INITIAL_POSITION to, I tried
private static final INITIAL_POSITION = 0;
but without any luck
When adding the initial fragment, you must not add it to the back stack.
You must only do it for the next ones. When the back stack will be empty, the Activity will just finish.
Edit: Here is an explanation of the problem so you can figure out how to fix it:
Each time you add a fragment transaction to the back stack, you allow the user to revert it by pressing the back button and the Activity will return to the state it was before the transaction. If the initial fragment is added to the back stack, then when the user press back, the screen becomes blank, because there was nothing displayed before you added the initial fragment. That's why the initial fragment transaction which adds the first visible fragment to your Activity must not be added to the back stack. Usually you initialize the initial fragment like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null) {
Fragment fragment = new FirstFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.frame_container, fragment)
.commit();
}
}
BladeCoders answer was more trying to tell me how the backstack works rather than answering my question, i ended up not adding any fragments to the back stack, .addToBackStack(null), and overriding back button in MainActivity, feels like a little bit of a hack but works perfectly
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() < 1){
Fragment fragment = new FirstFragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter, R.anim.exit,
R.anim.pop_enter, R.anim.pop_exit);
getSupportActionBar().setTitle(mDrawerTitle);
fragmentTransaction.replace(R.id.frame_container,
fragment).addToBackStack("first").commit();
}else{
finish();
}
}
You can do it even with out backstack its just my point of view to simplify so that it can help some one.
#Override
public void onBackPressed(){
Fragment f = getSupportFragmentManager().findFragmentById(R.id.container_body);
if(f.getClass().getName().equals(HomeFragment.class.getName())){ // here HomeFragment.class.getName() means from which faragment you actually want to exit
finish();
}else{
displayView(0); //were you want to go when back button is pressed
}
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.app_name);
break;
case 1:
fragment = new OffersFragment();
title = getString(R.string.nav_item_offers);
break;
case 2:
fragment = new NotificationFragment();
title = getString(R.string.nav_item_notifications);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
I'm developing an android application, I have a problem with the changing of back button function. How i can "replace" the default action of this button ?
I would realize a simple function that allow the user to return to the previous fragment when back button is pressed, for example :
[Main Fragment] ----> [2nd Fragment]
[2nd Fragment] <---- [Main Fragment]
I have read some question like this, but i don't understand how to solve my problem.
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment(getApplicationContext());
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
This is the part of my code where i call the "new fragment".
When i start up my application a new fragment is created (HomeFragment), in this frag i create a new fragment (Fragment_Detail).
What that i want is return from Fragment_Detail to HomeFragment.
I hope I was explanatory
Just add the addToBackStack(null). It will automatically go to the previous fragment loaded in stack.
HomeFragment fragment = new HomeFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.content, fragment,TAG)
.commit();
Refer addToBackStack() and refer this answer.
Refer the docs
You should take a look at the example: http://developer.android.com/training/implementing-navigation/temporal.html#back-fragments
I am trying to save the state on the navigation drawer fragments as I toggle between different fragments within the navigation drawer. For Example: I start at Fragment A fire some events, then toggle to Fragment B. Then I want to see the same state of Fragment A when I toggle back to Fragment A from Fragment B.
I tried using the onSavedInstanceState(Bundle savedInstanceState) but it only gets called when the orientation changes in the fragment life cycle. A new fragment gets created whenever I toggle to a new fragment and I can't figure out how to save data from a fragment and reload it on another visit.
I don't want to use backstack() either because it removes all the fragments up to the fragment that I want to restore.
Below is how I call the fragments on the drawer toggle.
private void selectItem(int position) {
Fragment fragment;
String TAG;
switch (position) {
case 0:
fragment = new FragmntA();
TAG = "A";
break;
case 1:
fragment = new FragmentB();
TAG = "B";
break;
case 2:
fragment = new FragmentC();
TAG = "C";
break;
case 3:
fragment = new FragmentD();
TAG = "D";
break;
case 4:
fragment = new FragmentE();
TAG = "E";
break;
default:
fragment = new FragmentA();
TAG = "A";
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, fragment, TAG);
ft.commit()
I don't know if there is any point in the fragment life cycle where I can save its state. Any help would be appreciated. Thanks.
To not loose the state of your fragments when switching from one to another you should do "new Fragment()" only once, and keep the instance in a global variable.
But this will not fix the rotation problem.
For the rotation problem, you should read this => http://blog.sqisland.com/2014/06/navigationdrawer-creates-fragment-twice.html
Not easy but I haven't found another way yet.
define fragment object as static in the class and in newInstance method only initialise is fragment is null otherwise just return the fragment.
This will solve your problem.
but for orientation change you will have to use on saveinstancestate method.
I have a drawer navigation with:
private void DisplayView (int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
...
From an activity I can throw that fragment (fragment2 for example)? With BeginTransaction?
Thanks
A Fragment cannot exist in it's own, eg. without an Activity. It cannot be fired up with an Intent like Activities do. You have to either create a new Activity to hold your new Fragment or replace the Fragment of your current Activity with the new one.
You cannot start fragment as an activity, they need to be added to activities.
Read more in the docs here
Also, see this