How to start a fragment from another activity - android

I want to start a fragment from B activity but the fragment is in main activity. If I use FragmentTransaction, but it gives error "No view found for ID for fragment"
Code
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.layoutContent, frag);
ft.commit();
Error
No view found for id 0x7f0e00be (com.company.app:id/layoutContent) for fragment PlaylistFrag{5764566 #0 id=0x7f0e00be}

If I understand your question, You want to start a fragment in an Activity from another Activity.
This is what I do to get Around that.
From the current Activity, I would start the other Activity on Click
Intent intent = new Intent (ActivityA.this, ActivityB.class);
intent.putExtra("EXTRA", "openFragment");
startActivity(intent);
In the destination Activity, listen for intent extras and start action.
switch (getIntent().getStringExtra("EXTRA")){
case "openFragment":
getSupportFragmentManager().beginTransaction().replace(R.id.replacableLayout, new FragmentActivityB()).commit();
getSupportActionBar().setTitle("Fragment Activity B");
break;
}
It works for me...

this will fire an exception as getSupportFragmentManager() is a function with the Activity you work on it so when you use ft.replace(R.id.layoutContent, frag); will look for layoutContent on current activity and will not found
i don't how u want to
Solution ==> - use Event Bus or Rxjava :) or may use a n interface with setter and getter and check it in another activity or use static variable to check the fragment you want to replaced to :)

Add this code in your onClick
// 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();
and add onBackPressed()
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}

Make Layout like below in MainActivity.java and its layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_add_workout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nujster.activity.AddWorkoutActivity">
<LinearLayout
android:id="#+id/add_workout_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"/>
</RelativeLayout>
Then, in main activity write below code to call fragment
public class AddWorkoutActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_workout);
getSupportFragmentManager().beginTransaction().add(R.id.add_workout_fragment, new LevelFragment(), "levels").addToBackStack(null).commit();
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().findFragmentByTag("levels") != null) {
LevelFragment levelFragment = (LevelFragment) getSupportFragmentManager().findFragmentByTag("levels");
if (levelFragment.isVisible()){
finish();
} else{
getSupportFragmentManager().popBackStack();
}
}
}
}

You can load same fragment in different activities.
Usually Fragment loads in Activity container.
Activity-1 layout have a container say R.id.layoutContent
Activity-2 layout also should have a container R.id.xxx
ft.replace(R.id.layoutContent[Container where fragment loads], frag);
May be Activity-2 do not have id of container

Related

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

Call a Fragment from an Activity (from OnClickListener)

I have a button inside my Activity and when I click on this button I want to call a Fragment.
For example if I want to call an Activity I can use the intent but if I want to call a Fragment, how can I do that?
I have checked other questions but I have not found an answer to what I'm asking.
btnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
What am I going to put inside this?
You can add your fragment dynamically.You want to create a fragment.
To programmatically add or remove a Fragment, you will need the FragmentManager and FragmentTransaction
XML Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/myFrame" <!-- Id which you're gonna use in Java -->
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me" />
</LinearLayout>
Java
btnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager ();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ();
MyFragment myfragment = new MyFragment(); //your fragment
// work here to add, remove, etc
fragmentTransaction.add (R.id.myFrame, myfragment);
fragmentTransaction.commit ();
}
});
See this doc
You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.
So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filters.
The answer to your problem is easy: replace the current Fragment with the new Fragment and push transaction onto the backstack. This preserves back button behaviour...
Creating a new Activity really defeats the whole purpose to use fragments anyway...very counter productive.
#Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new chartsFragment();
// consider using Java coding conventions (upper first char class names!!!)
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();
}
https://developer.android.com/guide/components/fragments.html#Transactions
Quotation

how to back to previous fragment on pressing manually back button

I have one activity and multiple fragments in my app. i want to back one by one fragments when pressing back button which in all fragments.
i used this code segment but when pressing back button it comes to main activity without back one by one. Also i want to change the icon when it's comes to the main activity.(msg_alert)
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = MainActivity.this
.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragment = new MainMenuLayout();
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
btnBack.setVisibility(View.VISIBLE);
btnBack.setImageResource(R.drawable.msg_alert);
tvTitle.setText("Layout 0");
}
});
Lets say you are having two fragments A and B. Fragment A is is attached at the startup of activity and on any user event you navigate to fragment B by replacing the Fragment A.
1) while adding Fragment B to the activity
// Works with either the framework FragmentManager or the
// support package FragmentManager (getSupportFragmentManager).
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragmentB, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
2) override the onBackPressed of the activity to handle the back button press event.
#override
public void onBackPressed() {
// is there any fragment in backstack, if yes popout.
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
return;
}
super.onBackPressed();
}
this is one more option ,
in the Activity.
Fragment secondfragment= new SecondFragmnet();
#Override
public void onBackPressed() {
if(secondfragment.isVisible()){
// replace 1st fragment
}else{
// Alert dialog for Exit App
}
// you can check multiple fragments.
Hope it helps you
You have to Use addToBackStack() method while doing Transaction Between Fragments...
Read This : Implement Back Navigation for Fragments
Use Following code when you use Fragment Transaction...
String backStateName = fragment.getClass().getName(); // getting Fragment Name..
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment)
.addToBackStack(backStateName) //adding it to BackStack..
.commit();
In Fragments we dont have back navigation..
We can acheive that through replace() method.
I seen in your code that you are only replace the content frame. and so the result is backpress it comes to activity.
Also be sure that you have your mannual back button in the activity
this is test xml for activity
<?xml version="1.0" encoding="utf-8"?>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
<FrameLayout
android:id="#+id/activity_main_content_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
Use
Fragment fragment = new MainMenuLayout();
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.addToBackStack(null);// TODO parameter here it tag of fragment or null or "" String
ft.commit();
For more information about fragments backstack go through this android developer refrence :-Fragment BackStack

Fragments are getting overlapped on back button

I have created 3 Fragments namely (FragmentA, FragmentB, FragmentC) and one MainActivity.
There is a button in each fragment which replaces itself with next Fragment till FragmentC.
I am replacing FragmentA (with) FragmentB (then with) FragmentC.
Transaction from FragmentA to FragmentB uses below function
#Override
public void fragmentreplacewithbackstack(Fragment fragment, String tag) {
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.contner,fragment , tag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
// fragmentManager.executePendingTransactions();
}
Transaction from FragmentB to FragmentC uses below function
public void fragmentreplace(Fragment fragment,String tag){
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.contner,fragment , tag);
fragmentTransaction.commit();
}
problem is when i press back button from FragmentC, FragmentC and FragmentA overlap with each other.
You need to add Fragment C to backstack as well if you wanna go to Fragment B on back press from here.
So call the below for Fragment C as well.
fragmentTransaction.addToBackStack(null);
EDIT - Change this current method you are using to go from B to C,
public void fragmentreplace(Fragment fragment,String tag){
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.contner,fragment , tag);
fragmentTransaction.addToBackStack(null); //this will add it to back stack
fragmentTransaction.commit();
}
I had the same problem and this answer of Budius helped me a lot.
You can solve your issue in the following way:
1) Instantiate the following listener (you have to keep reference of the FragmentC's instance) and, since fragmentA is the only fragment added to the backstack, when the user presses the back button, the number of transactions in the backstack will be zero
private OnBackStackChangedListener backStackChangedListener = new OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount()==0) {
if(fragmentC!=null) {
getSupportFragmentManager().beginTransaction().remove(fragmentC).commit();
}
}
}
};
2) Add the listener in the MainActivity when the latter is started
getSupportFragmentManager().addOnBackStackChangedListener(backStackChangedListener);
3) Remove the listener when the activity is stopped
why don't you just make a fragment activity with a frame layout in which you can replace that frame with any fragment..
Screen extends FragmentActivity
{
protected void onCreate(Bundle b)
{
super.onCreate(b);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.work);
callPerticularScreen(screenNumber,false,null,null);
}
public void callPerticularScreen(int screenNumber,boolean addToBackStack,String nameTag,Bundle b)
{
switch(screenNumber)
{
case registrationScreen:
callFragForMiddleScreen(registrationPageFrag,addToBackStack,nameTag);
break;
case dashboardScreen:
callFragForMiddleScreen(dashboardFrag,addToBackStack,nameTag);
break;
default:
break;
}
}
}
now from any fragment screen you can call this function to replace your fragment with another..like..
private void callFragForMiddleScreen(Fragment frag,boolean addToBackStack,String nameTag)
{
transFragMiddleScreen=getFragManager().beginTransaction();
transFragMiddleScreen.replace(getMiddleFragId(),frag);
if(addToBackStack)
{
transFragMiddleScreen.addToBackStack(nameTag);
}
transFragMiddleScreen.commit();
//getFragManager().executePendingTransactions();
}
from your fragement just call
Frag1 extends Fragment
{
onActivityCreate()
{
middleScreen=(Screen) getActivity();
middleScreen.callPerticularScreen(1,true,"tag");
}
}
layout for fragment activity..
<RelativeLayout
android:id="#+id/rl2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/rl" >
<FrameLayout
android:id="#+id/middle_screen"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</RelativeLayout>
just don't add the fragment B to back stack so that you can come from c-> a directly.
25 support library
for example if you have
A -> B -> C
A id is 0
B id is 1
C id is 2
to rollback to A fragment just call
getFragmentManager().popBackStackImmediate(0 /* ID */, 0 /* flag */);
0 - is ID of backstack entry to rollback
or
popBackStackImmediate(1, FragmentManager.POP_BACK_STACK_INCLUSIVE)
FragmentManager.POP_BACK_STACK_INCLUSIVE, it means you want also remove supplied ID
also you can call
getFragmentManager().popBackStackImmediate("stack_name", 0)
"stack_name" it's a name of backstack to revert
for example
A -> B -> C -> D
A in MAIN_BACK_STACK
B in MAIN_BACK_STACK
C in SEPARATE_BACK_STACK
D in SEPARATE_BACK_STACK
if you want to revert to fragment B
just call
getFragmentManager().popBackStackImmediate("MAIN_BACK_STACK", 0)
or
getFragmentManager().popBackStackImmediate("SEPARATE_BACK_STACK", FragmentManager.POP_BACK_STACK_INCLUSIVE)

How to replace fragment C with fragment A when back button is pressed?

My scenario : Activity 1 consists of Fragments A-> B-> C. All the fragments are added using this code :
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content, fragment, TAG);
ft.addToBackStack(TAG);
ft.commit();
Now, from fragment C, I want to directly return to Fragment A. Therefore, I've commented ft.addToBackStack(TAG) while adding Fragment C. So when I press back button from C I directly get Fragment A on the screen.
However, Fragment C is not replaced by A. In fact, both the fragments are visible. How do I solve this issue?
You need to do 2 things - name the FragmentTransaction from A->B and then override onBackPressed() in your containing activity to call FragmentManager#popBackStack (String name, int flags) when you are on Fragment C. Example:
Transition from A->B
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, new FragmentB(), "FragmentB")
.addToBackStack("A_B_TAG")
.commit();
Transition from B->C will use a similar transaction with "FragmentC" as its tag.
Then in your containing Activity override onBackPressed():
#Override
public void onBackPressed() {
if (getSupportFragmentManager().findFragmentByTag("FragmentC") != null) {
// I'm viewing Fragment C
getSupportFragmentManager().popBackStack("A_B_TAG",
FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
super.onBackPressed();
}
}
Theory
Use the addToBackStack(tag: String): FragmentTransaction method from within the FragmentTransaction in order to mark a point where you want to return to. This method returns the FragmentTransaction instance for chain-ability only.
Then Return with the popBackStackImmediate(tag: String, flag: int): void method from the FragmentManager. The tag is what you specified before. The flag is either the constant POP_BACK_STACK_INCLUSIVE to include the transaction marked or 0.
Example
What follows is an example with the following layout having a FrameLayout with id content_frame where the fragments are loaded into.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<FrameLayout
android:id="#+id/content_frame"
android:layout_below="#id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
The code below marks a fragment by it's fragment class name when replacing the content of the layout element with id content_frame.
public void loadFragment(final Fragment fragment) {
// create a transaction for transition here
final FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
// put the fragment in place
transaction.replace(R.id.content_frame, fragment);
// this is the part that will cause a fragment to be added to backstack,
// this way we can return to it at any time using this tag
transaction.addToBackStack(fragment.getClass().getName());
transaction.commit();
}
And to complete this example a method that allows you to get back to that exact same fragment using the tag when you loaded it.
public void backToFragment(final Fragment fragment) {
// go back to something that was added to the backstack
getSupportFragmentManager().popBackStackImmediate(
fragment.getClass().getName(), 0);
// use 0 or the below constant as flag parameter
// FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
When implementing this for real you might want to add a null check on the fragment parameter ;-).
This is how I do it..
With FragmentA.java and any other fragments.
Replace your fragment with its class name as tag:
private void showFragment(Fragment fragment){
if(fragment != null){
getSupportFragmentManager().beginTransaction().replace(R.id.container,fragment,fragment.getClass().getSimpleName()).commit();
}
}
Now in onBackPressed():
#Override
public void onBackPressed()
{
if(getSupportFragmentManager().findFragmentByTag("FragmentA") == null)
showFragment(new FragmentA());
else
super.onBackPressed();
}

Categories

Resources