Get previous fragment android - android

I have a Layout were i keep swapping my two Fragments MainFragment and SecondFragment
I have an Activity Level Button and with its onclick I swap these fragments in the layout.
But I need to keep the same instance of FragA every time I switch back from FragB.
Below is the code that i used but the application crashes with a NullPointerError.
// When journey button menu is clicked [INSIDE THE MAIN ACTIVITY]
OnClickListener journeyBtnClick = new OnClickListener() {
#Override
public void onClick(View arg0) {
if(currentType==0){
InitThisFragment(1);
}else{
InitThisFragment(0);
}
}
};
private int currentType=0;
public void InitThisFragment(int type){
if(type==0){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//get the previously added MainFragment from the BackStack
Fragment mainFragment= getSupportFragmentManager().findFragmentByTag("main");
transaction.replace(R.id.abs_fragment_container,mainFragment);
transaction.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
transaction.commit();
}else{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.abs_fragment_container, new SecondFragment());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
}
currentType=type;
}
Before this I initialize the MainFragment in the OnCreate() of my Activity class;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.abs_fragment_container, new MainFragment());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); //add MainFragment in the BackStack
transaction.addToBackStack("main");
transaction.commit();
}
I the user clicks the Button
Initiate a New Fragment of the SecondFragment [No History of the
Previous Fragment]
Go Back to the MainFragment [In same state as it was while leaving
it]
Please help!
Thanks in advance.

If I have understood what you want to do, you can just call "FragmentManager.popBackStack()" if you are in the secondFragment.
So:
public void InitThisFragment(int type){
if(type==0){
getFragmentManager().popBackStack();
}else{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.abs_fragment_container, new SecondFragment());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
}
currentType=type;
}

Put "main" tag in replace method.
transaction.replace(R.id.abs_fragment_container, new MainFragment(),"main");
tag parameter would work different for addToBackStack and replace method. According to android for tag parameter :
addToBackStack: An optional name for this back stack state, or null.
replace: Optional tag name for the fragment, to later retrieve the fragment with FragmentManager.findFragmentByTag(String).

Related

Navigating between two fragments on backpress

I am having trouble going back to previous fragment on backpress from current fragment.
I have Two fragments and i navigate to second fragment on click and when i try to click back from the second fragment, i want to go back to the previous fragment but instead the app exits on backpress. below is the code i am using..
Fragment1 calling second fragment
UserFragment frag = new UserFragment()
FragmentTransaction transaction = getFragmentManager().beginTransaction();
frag.setArguments(bundle);
transaction.addToBackStack("UserActivity");
transaction.replace(android.R.id.content, frag, "UserActivity").addToBackStack(null);
transaction.commit();
In second Fragment i have implemented an interface OnBackpress and over riding the below method
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() != 0) {
if(getFragmentManager().findFragmentByTag("UserActivity") != null){
Log.e("UserActivity",getFragmentManager().findFragmentByTag("UserActivity").toString());
getFragmentManager().popBackStack();
};
}
}
But on back press the app exits. Instead i want to go back to previous fragment. What mistake am i doing? please help. thanks
You need to add you first fragment to back stack properly, you are doing it wrong in your first part of the code.
Use the following code instead.
UserFragment frag = new UserFragment()
FragmentTransaction transaction = getFragmentManager().beginTransaction();
frag.setArguments(bundle);
transaction.addToBackStack("UserActivity");
transaction.replace(android.R.id.content, frag, "UserActivity");
transaction.commit();
Also there is no need to add any code in your onBackPressed after above change.
First, you need to add your fragments to the backstack:
public static void addFragment(FragmentManager fragmentManager, Fragment fragment, int id){
fragmentManager.beginTransaction().add(id, fragment).addToBackStack(null).commit();
}
Then you need to override the onBackPressed, which is a method gets called whenever a user clicks the back button:
#Override
public void onBackPressed() {
super.onBackPressed();
if(getSupportFragmentManager().getBackStackEntryCount() == 0){
button.setVisibility(View.VISIBLE);
}
}
please change to add() instead of replace() in your code..
UserFragment frag = new UserFragment()
FragmentTransaction transaction = getFragmentManager().beginTransaction();
frag.setArguments(bundle);
transaction.addToBackStack("UserActivity");
transaction.add(android.R.id.content, frag, "UserActivity").addToBackStack(null);
transaction.commit();
This will solve your problem.

Difference between add vs addToBackStack

Hi I have read this Difference between add(), replace(), and addToBackStack(). I have a confusion that If I add multiple fragments like below then If I press back button from fragment2 then will fragment1 will open ? If so then what is the use of addToBackStack as add already maintaining a stack.
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment1 = new Fragment();
ft.add(R.id.llContainer, fragment1, "fragment_one");
Fragment fragment2 = new Fragment();
ft.add(R.id.llContainer, fragment2, "fragment_two");
ft.commit();
Well if you call multiple times add method on FragmentTransaction like this
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment1 = new Fragment();
ft.add(R.id.llContainer, fragment1, "fragment_one");
Fragment fragment2 = new Fragment();
ft.add(R.id.llContainer, fragment2, "fragment_two");
ft.commit();
then both the fragments that been added to FragmentTransaction will be shown as overlapping.
Now clicking back will close the application. It won't start the previous fragment.
Hope this is what you were looking for.
Add method will not add your Fragment in BackStack. You need to verify once again.
While looking into code of addToBackStack
#Override
public FragmentTransaction addToBackStack(String name) {
if (!mAllowAddToBackStack) {
throw new IllegalStateException(
"This FragmentTransaction is not allowed to be added to the back stack.");
}
mAddToBackStack = true;
mName = name;
return this;
}
Flag mAddToBackStack = true; enabled which value is false by default. And this is the flag which is being used to add fragment into backstack. Have a look into below methods calls
#Override
public int commit() {
return commitInternal(false);
}
int commitInternal(boolean allowStateLoss) {
......
if (mAddToBackStack) {
mIndex = mManager.allocBackStackIndex(this);
} else {
mIndex = -1;
}
.....
}
So what you observed is not correct. Something you are missing

Fragments overlapping while using replace() [duplicate]

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();

Issue in Fragments in android

When I click on the back icon in the layout then it goes to previous fragment but it doesn't go to the fragment it was killed. what is the solution for this?
I'm using finish() and backstack but it not works for me
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
android.support.v4.app.Fragment onlineFragments = new OnlineFragments();
android.support.v4.app.FragmentManager fragmentManagerprofile = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentprofileTransaction = fragmentManagerprofile.beginTransaction();
fragmentprofileTransaction.replace(R.id.background_fragment, onlineFragments);
fragmentprofileTransaction.commit();
}
});
Fragment A
case R.id.recharge:
HomeActvity.toolbar.setVisibility(View.GONE);
android.support.v4.app.Fragment Recharge = new Prepaid_recharge();
android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, Recharge);
fragmentTransaction.commit();
break;
Whenever your making Transactions between fragments and you want to navigate back to the previous fragment(s) (Back Button), in the transaction, you must add this transaction to the backStack before committing:
Android docs:
"Before you call commit(), however, you might want to call addToBackStack(), in order to add the transaction to a back stack of fragment transactions. This back stack is managed by the activity and allows the user to return to the previous fragment state, by pressing the Back button."
https://developer.android.com/guide/components/fragments.html#Transactions
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
I use this code to add and remove the fragment. In case I do not need that fragment to be in the back stack I send the boolean value as false. Doing this when pressing back button from toolbar It open the correct activity
public static void changeFragment (MyActivity activity, Fragment fragment, int fragmentContainer, boolean addToBackStack){
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(fragmentContainer, fragment);
/*here we keep track of fragments and avoiding last blank fragment by passing true*/
if(addToBackStack){
fragmentTransaction.addToBackStack(null);
}
fragmentTransaction.commit();
}

android fragment handle back button press not working

I am working fragment, I replaced FragmentA by fragment B.it's working perfect,but when I press back button I can't back Fragment A.
I tried to override onKeyDown method,but I can't override this method in fragment
this is a my source
CategoryViewPager fragment1 = new CategoryViewPager();
FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction().addToBackStack("method");
ft.setCustomAnimations(R.anim.trans_left_in, R.anim.trans_left_out);
ft.replace(R.id.content_frame, fragment1, "fragment2");
ft.commit();
when I use CategoryViewPager and click back button I can't go back(fragment wich i replaced this fragment)
how can I solve my problem?
Call addToBackStack() before you commit the transaction:
getSupportFragmentManager().beginTransaction()
// Add this transaction to the back stack
.addToBackStack()
.commit();
No need to use tag in your case. just use like this
/*
* Add this transaction to the back stack.
* This means that the transaction will be remembered after it is
* committed, and will reverse its operation when later popped off
* the stack.
*/
fragmentTransaction.addToBackStack(null);
It is better to handle back button press through your activity unless your actvity host large number of fragments.When you press back button inside your fragment onBackPressed() method of your activity will be called which can be overridden and handled..So handling back button for fragments can be done in this way..
MainActvity
public static boolean isMainActivityShown ;
public static boolean isFragment1Shown=false ;
public static boolean isFragment2Shown=false ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isMainActivityShown=true //inside onCreate method put isMainActivityShown true
.
.
.
}
.
.
Fragment currentFragment = new Fragment1();
isMainActivityShown=false; //when moving to fragment1
isFragment1Shown=true;
frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
.commit();
#Override
public void onBackPressed() {
if(isMainActivityShown)
{
finish();
}
else if(isFragment1Shown)
{
//write the code to handle back button when you are in Fragment1
}
else if(isFragment2Shown)
{ //When you are in Fragment 2 pressing back button will move to fragment1
Fragment currentFragment = new Fragment1();
isFragment2Shown=false;
isFragment1Shown=true;
FragmentManager frgManager;
frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
.commit();
}
}
Fragment1
Fragment currentFragment = new Fragment2();
MainActivity.isFragment1Shown=false;
MainActivity.isFragment2Shown=true;
frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
.commit();
Check this link
Check the addToBackStack(String name) method. This should solve your problem.

Categories

Resources