I am trying to show a new fragment where the nav_host_fragment is but I want the old one to show whenever I click on backButton or on an X in my app (I added that already).
In the state that it is in right now it won't let me get out of the PlaylistFragment.
I also tried around with FragmentTransaction.add(...) but I couldn't figure how I get this working
My Code:
MainActivity.java:
Fragment fragment = new PlayListFragment(position);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment oldFragment = fragmentManager.findFragmentByTag(fragment.getClass().getName());
//if oldFragment already exits in fragmentManager use it
if (oldFragment != null) {
//fragment = oldFragment;
}
fragmentTransaction.replace(R.id.nav_host_fragment, fragment, fragment.getClass().getName());
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.addToBackStack("playlist");
fragmentTransaction.commit();
PlaylistFragment.java:
getActivity().getSupportFragmentManager().popBackStack("playlist", 0);
EDIT:
When I tried putting null instead of "playlist" in the backstack:
Yup. Then I see both fragments overflowing each other:
Normal state:
https://prnt.sc/12yitg5
When clicking on the "downloaded songs":
https://prnt.sc/12yiu79
When clicking back in the fragment:
https://prnt.sc/12yiuy6
EDIT: When I click on the X again it shows me the home fragment while bottom nav highlights the Library tab.
I have a few fragments in one activity. In Main Activity I implemented popBackStack(); in onBackPressed();
So that, you can always go back to previous fragment clicking back button. But popBackStack(); doesn't remove the fragment I just left.
How to achieve removing current fragment each time, we click back
button?
public void removeFragmentbyTag(String myFrag){
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove(myFrag);
trans.commit();
manager.popBackStack();
}
hope this bit of code help you.
I'm attempting to implement a back stack while using fragments, but when using the Back button, I keep getting taken out of the app to the home screen.
Activity opens fragment A; Fragment A has a clickable TextView that opens fragment B (this works). Hitting BACK should return me to fragment A, but it takes me to the home screen instead.
Here is the activity's call to the opening of fragment A in onCreate:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_layout_container, new FragmentLogin(), "fragment_login")
.addToBackStack("login_screen")
.commit();
Log.d("Back", getFragmentManager().getBackStackEntryCount() +" <- Entry Count at LoginActivity.onCreate" );
At this point, the Log prints 0 <- Entry Count at LoginActivity.onCreate. Something I've done wrong keeps this from printing 1.
Then, the Fragment A has this listener:
forgottenPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_layout_container, new FragmentForgottenPassword(), "fragment_password")
.addToBackStack("forgotten_password")
.commit();
Log.d("Back", getFragmentManager().getBackStackEntryCount() + " <- Entry Count at FragmentLogin.onCreateView.Listener");
}
});
The Log here prints 1 <- Entry Count at FragmentLogin.onCreateView.Listener. Here, the listener works and opens fragment B - but the back button returns me to the home screen.
Use this in your Activity it should pop out the fragments already added to backstack
#Override
public void onBackPressed()
{
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Try Like This,
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
} else {
getFragmentManager().popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
transaction.replace(R.id.fragment_layout_container, fragment);
transaction.commitAllowingStateLoss();
getFragmentManager().executePendingTransactions();
}
and Used it like this,
replaceFragment(new FragmentForgottenPassword(), true);
There is a GitHub library that will do this work for you!https://github.com/rathodchintan/Fragment-Back-StackWhenever you are displaying any new fragment, just push that fragment into stack using following code.
//here this fragment is our first fragment
homeListFragment = new HomeListFragment();
fragmentStack.push(homeListFragment);It has many other stack options too.
Having Navigation drawer in Activity and changing Fragments by these lines of code
switch (menuItem.getItemId()) {
case R.id.home:
menuItem.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
if (getSupportFragmentManager().findFragmentByTag("ranking") == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.list_view_container, new HomeFragment(),
"ranking")
.addToBackStack("ranking")
.setTransition(
FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
} else {
getSupportFragmentManager().popBackStack("ranking", 0);
}
return true;
case R.id.current_event:
menuItem.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
if (getSupportFragmentManager().findFragmentByTag("ranking1") == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.list_view_container, new CurrentEvents(),
"ranking1")
.addToBackStack("ranking1")
.setTransition(
FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
} else {
getSupportFragmentManager().popBackStack("ranking1", 1);
}
return true;
}
I wanted Fragment to remain in memory so that it should not rebuilt again and again and fetch data from internet again and again so I have put the above method to get that but now, when I am changing the fragment by navigation drawer one fragment is replacing another and goes on and also I have to press back button=number of times new fragment created to exit from application. I want fragment in Backstack but not like this which is replacing one another. I want just one method at time. please help
Since you're using add(), the previous Fragment will not be removed from the container.
You should replace the calls to add() with replace(). For example, case R.id.home would become:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.list_view_container, new HomeFragment(),
"ranking")
.addToBackStack("ranking")
.setTransition(
FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
I wanted Fragment to remain in memory so that it should not rebuilt again and again and fetch data from internet again and again
You could try Fragment's setRetainInstance(true) to do that but it's not recommended (and I've never used it).
The other way which is more appropriate is to use Fragment's onSaveInstanceState(). You can read about it at Developer Android.
You can Check This Scenario, Hopefully it solve your Problem:-
Try to Attach and Detach the Fragment from FragmentTransaction. When
you Move to Next Fragment detach the last one Fragment From
FragmentTransaction and when you wants to use it again then attach it.
See sample code for how to Detach and Attach the Fragment, It will
help you :
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
AndroidFragment androidFragment = (AndroidFragment) fm.findFragmentByTag("android");
AppleFragment appleFragment = (AppleFragment) fm.findFragmentByTag("apple");
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
/** Detaches the androidfragment if exists */
if(androidFragment!=null)
ft.detach(androidFragment);
/** Detaches the applefragment if exists */
if(appleFragment!=null)
ft.detach(appleFragment);
/** If current tab is android */
if(tabId.equalsIgnoreCase("android")){
if(androidFragment==null){
/** Create AndroidFragment and adding to fragmenttransaction */
ft.add(R.id.realtabcontent,new AndroidFragment(), "android");
}else{
/** Bring to the front, if already exists in the fragmenttransaction */
ft.attach(androidFragment);
}
}else{ /** If current tab is apple */
if(appleFragment==null){
/** Create AppleFragment and adding to fragmenttransaction */
ft.add(R.id.realtabcontent,new AppleFragment(), "apple");
}else{
/** Bring to the front, if already exists in the fragmenttransaction */
ft.attach(appleFragment);
}
}
ft.commit();
`For Reference see this onTabChanged :` [http://wptrafficanalyzer.in/blog/creating-navigation-tabs-using-tabhost-and-fragments-in-android/][1]
I have a fragment inside a group activity and I want to replace it with another fragment:
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
SectionDescriptionFragment bdf = new SectionDescriptionFragment();
ft.replace(R.id.book_description_fragment, bdf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
It works fine when it is done as a seperate project without using activity group, every thing works fine in log cat as control goes inside getview(), but no view is visible, not even any exception arises, I want the book detail fragment to be replaced by section detail fragment.
Xml of book detail fragment has id book_description_fragment and xml for section description fragment has id section_description_fragment.
The above code is in onClick method of an item, I want that when user taps on an item in horizontal scroll view, then the fragment changes.
Fragments that are hard coded in XML, cannot be replaced. If you need to replace a fragment with another, you should have added them dynamically, first of all.
Note: R.id.fragment_container is a layout or container of your choice in the activity you are bringing the fragment to.
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Please see this Question
You can only replace a "dynamically added fragment".
So, if you want to add a dynamic fragment, see this example.
I've made a gist with THE perfect method to manage fragment replacement and lifecycle.
It only replace the current fragment by a new one, if it's not the same and if it's not in backstack (in this case it will pop it).
It contain several option as if you want the fragment to be saved in backstack.
=> See Gist here
Using this and a single Activity, you may want to add this to your activity:
#Override
public void onBackPressed() {
int fragments = getSupportFragmentManager().getBackStackEntryCount();
if (fragments == 1) {
finish();
return;
}
super.onBackPressed();
}
Use the below code in android.support.v4
FragmentTransaction ft1 = getFragmentManager().beginTransaction();
WebViewFragment w1 = new WebViewFragment();
w1.init(linkData.getLink());
ft1.addToBackStack(linkData.getName());
ft1.replace(R.id.listFragment, w1);
ft1.commit();
Use ViewPager. It's work for me.
final ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.vp_pager);
button = (Button)result.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(1);
}
});
hope you are doing well.when I started work with Android Fragments then I was also having the same problem then I read about
1- How to switch fragment with other.
2- How to add fragment if Fragment container does not have any fragment.
then after some R&D, I created a function which helps me in many Projects till now and I am still using this simple function.
public void switchFragment(BaseFragment baseFragment) {
try {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
if (getSupportFragmentManager().findFragmentById(R.id.home_frame) == null) {
ft.add(R.id.home_frame, baseFragment);
} else {
ft.replace(R.id.home_frame, baseFragment);
}
ft.addToBackStack(null);
ft.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
enjoy your code time :)
you can use simple code its work for transaction
Fragment newFragment = new MainCategoryFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame_NavButtom, newFragment);
ft.commit();
You Can Use This code
((AppCompatActivity) getActivity()).getSupportFragmentManager().beginTransaction().replace(R.id.YourFrameLayout, new YourFragment()).commit();
or You Can This Use Code
YourFragment fragments=(YourFragment) getSupportFragmentManager().findFragmentById(R.id.FrameLayout);
if (fragments==null) {
getSupportFragmentManager().beginTransaction().replace(R.id.FrameLayout, new Fragment_News()).commit();
}
I change fragment dynamically in single line code
It is work in any SDK version and androidx
I use navigation as BottomNavigationView
BottomNavigationView btn_nav;
FragmentFirst fragmentFirst;
FragmentSecond fragmentSecond;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
fragmentFirst = new FragmentFirst();
fragmentSecond = new FragmentSecond ();
changeFragment(fragmentFirst); // at first time load the fragmentFirst
btn_nav = findViewById(R.id.bottomNav);
btn_nav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch(menuItem.getItemId()){
case R.id.menu_first_frag:
changeFragment(fragmentFirst); // change fragmentFirst
break;
case R.id.menu_second_frag:
changeFragment(fragmentSecond); // change fragmentSecond
break;
default:
Toast.makeText(SearchActivity.this, "Click on wrong bottom SORRY!", Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
public void changeFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout_changer, fragment).commit();
}
In kotlin you can do:
// instantiate the new fragment
val fragment: Fragment = ExampleFragment()
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.book_description_fragment, fragment)
transaction.addToBackStack("transaction_name")
// Commit the transaction
transaction.commit()
This will work if you're trying to change the fragment from another fragment.
Objects.requireNonNull(getActivity()).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.home_fragment_container,new NewFragment())
NOTE As stated in the above answers, You need to have dynamic fragments.
You can use fragment-ktx
// If you are in fragmet
childFragmentManager.beginTransaction()
// or if you are in activiry
supportFragmentManager.beginTransaction()
// Create and commit a new transaction
supportFragmentManager.commit {
setReorderingAllowed(true)
// Replace whatever is in the fragment_container view with this fragment
replace<ExampleFragment>(R.id.fragment_container)
}
To replace a fragment with another one do this, Note that R.id.fragment comes from the id that you give to the first tag of the fragment in the XML.
barAudioPlaying.setOnClickListener(view -> {
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment,new HomeFragment())
.commit();