How to add a instant of fragment again? - android

I have a problem with a fragment. I need to display a fragment many times and don't create new instant of it. I have a method that it use to change the content of activity.
protected void setContentFragment(Fragment contentFragment) {
this.contentFragment = contentFragment;
setContentView(R.layout.content_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, contentFragment).commit();
getSlidingMenu().showContent();
}
content_frame is a simple layout.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
The problem is: I create instant of the first Fragment and pass it to setContentFragment(...) (still keep instant of this). Then call setContentFragment with other Fragment. And now, I pass instant of the first Fragment to this method, it show bank screen. Please help me :(

Try This..
private void switchFragment(Fragment fragment) {
if (getActivity() == null)
return;
if (getActivity() instanceof MainActivity) {
DashboardActivity dashboard = (MainActivity) getActivity();
dashboard.switchFragment(fragment, "Main List");
}
}

do this
protected void setContentFragment(Fragment contentFragment) {
this.contentFragment = contentFragment;
Random random = new Random(100);
String rString = "myRandomString"+random.nextInt(); // Create a random string here everytime you call setContentFragment
setContentView(R.layout.content_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, contentFragment, rString).commit();
getSlidingMenu().showContent();
}
This will replace the fragment as you require
Reference: http://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html#replace%28int,%20android.support.v4.app.Fragment,%20java.lang.String%29

When swapping fragments you need to detach/reattach instead of replacing them. This leaves it in memory. Also you don't need to setContentView again, just leave the existing FrameLayout ( you could also use android.R.id.content for the main activity content view, instead of creating a FrameLayout)
Fragment content1, content2;
Fragment current=content1;
public void onCreate() {
if(savedInstanceState==null)
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, content1)
.commit();
}
public void swap() {
if(current==content1) {
getSupportFragmentManager().beginTransaction()
.detach(content1)
.attach(android.R.id.content, content2)
.commit();
current=content2;
} else {
getSupportFragmentManager().beginTransaction()
.detach(content2)
.attach(android.R.id.content, content1)
.commit();
current=content1;
}
}

Related

Changing data dynamically on flip card Fragments using Android

I am trying to use flip animations in Android for practising vocabulary. I have made a container for my Fragments:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="100dp"
android:onClick="flipCard"
/>
and two Fragments: fragment_card_flip.xml and fragment_card_back.xml. One is for showing the word and the other, the meaning on the back of the card.
I am getting a word from database randomly and want to change the text in both Fragments i.e., put the word on the front Fragment and the meaning on the back Fragment. In the onClick() in the Fragment I am calling a flipcard() function:
public void flipCard(View view) {
if (mShowingBack) {
getFragmentManager().popBackStack();
mShowingBack=false;
f = (Fragment) getFragmentManager().findFragmentById(R.id.container);
if(f!=null)
((TextView) f.getView().findViewById(R.id.text)).setText(w);
return;
}
// Flip to the back.
mShowingBack = true;
getFragmentManager().beginTransaction().setCustomAnimations(
R.animator.card_flip_right_in,
R.animator.card_flip_right_out,
R.animator.card_flip_left_in,
R.animator.card_flip_left_out)
.replace(R.id.container, new CardBackFragment())
.addToBackStack(null)
.commit();
}
This is my attempt to change the word only, not the definition. But I can't change the text data of the Fragment dynamically. Please help me to update both my Fragments dynamically with a new word/meaning from the database.
I think the first step is to change your Fragments so that they take the word they will display as an argument:
public class CardFlip extends Fragment {
public static String ARGUMENT_WORD = "ARGUMENT_WORD"
public static CardFlip instantiate(String text) {
CardFlip cardFlip = new CardFlip();
Bundle argsBundle = new Bundle();
argsBundle.putString(ARGUMENT_WORD, text);
cardFlip.setArguments(argsBundle);
return cardFlip;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String text = getArguments().getString(ARGUMENT_WORD);
((TextView) findViewById(R.id.text)).setText(text);
}
}
Do this for both Fragments. Now you can make fragments dynamically with the words you want.
Now all you need to do is refactor your flipcard() method so that it uses the static instantiate method rather than the new CardFlip() constructor. Since you always want your Fragments to be up-to-date with the latest words, don't use popBackStack() use FragmentManager.beginTransaction().replace(). Something like this:
public void flipCard(View view) {
Fragment frag;
if (mShowingBack) {
frag = CardFlip.instantiate(currentWord);
}
else {
frag = CardBack.instantiate(currentWord);
}
getFragmentManager().beginTransaction()
.replace(R.id.fragment_container, frag)
.commit();
}
Then all you need is some logic for when to change the word randomly.
These are all concepts from the official developer's guide so you study this very carefully: consider reading the guide there multiple times and taking notes.

Android - How to call a fragment from inside a fragment?

I have a fragment that displays Card Views, something like a dashboard. Each Card View should replace the dashboard fragment and call its own fragment when it's clicked, however I can't seem to do it.
I tried the following:
imageId.Click += delegate {
((FragmentActivity)Activity).ShowFragment(SmokeSensor);
};
The method in the activity:
public void ShowFragment(SupportFragment fragment) {
var transaction = SupportFragmentManager.BeginTransaction();
connectionStatus.Visibility = ViewStates.Gone;
if (!ConnectionDetector.IsConnected(this)) {
connectionStatus.Visibility = ViewStates.Visible;
transaction.Detach(currentFragment);
transaction.Commit();
drawerLayout.CloseDrawer(leftDrawer);
return;
}
if (fragment == currentFragment) {
transaction.Detach(currentFragment);
transaction.Attach(currentFragment);
transaction.Commit();
drawerLayout.CloseDrawer(leftDrawer);
return;
}
transaction.SetCustomAnimations(Resource.Animation.slide_in, Resource.Animation.slide_out);
transaction.Replace(Resource.Id.fragment_container, fragment);
transaction.Commit();
drawerLayout.CloseDrawer(leftDrawer);
currentFragment = fragment;
}
you can create a public method in your main activity and call the method to replace or load fragments on an event in your current fragment.
For nested fragments use the child fragment manager on you root fragment.

To many instances of Fragment

I have one Activity with Fragment:
onCreate()
{
getSupportFragmentManager().beginTransaction()
.add(R.id.container, PostsGaleryFragment.newInstance(), FRAGMENT_TAG).addToBackStack("home")
.commit();
}
After user's action I call:
public void onShowPostRequested(ShowPost pShowPost)
{
SinglePostFragment singlePostFragment = SinglePostFragment.newInstance(pShowPost.getPostId());
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, singlePostFragment, FRAGMENT_TAG)
.addToBackStack(null)
.commit();
}
Then navigation can be made backward to home:
#Override
public void onBackPressed()
{
FragmentManager supportFragmentManager = getSupportFragmentManager();
if (supportFragmentManager.getBackStackEntryCount() > 0)
{
supportFragmentManager.popBackStack();
} else
{
super.onBackPressed();
}
}
Problem:
There is more than one instance of "home" Fragment. That is not good for me as every one of those fragments keep lot of references to quite big bitmaps and there is an OOM error waiting just behind the corner.
Questions:
Why old instance of Fragment is not used after .popBackStack()?
I temporary made a workaround with something like singleton pattern - works ok for now, but are there any disadvantages I should be aware of?
i guess what you are missing is check for onSavedInstance, try same as below
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, PostsGaleryFragment.newInstance(), FRAGMENT_TAG).addToBackStack("home")
.commit();
}
onCreate()
{
FragmentManager fm = getSupportFragmentManager();
PostGalleryFragment f = fm.findFragmentByTag(FRAGMENT_TAG);
if(f == null) {
f = fm.beginTransaction().add(R.id.container,
PostsGaleryFragment.newInstance(), FRAGMENT_TAG).commit();
}

Refresh Fragment at reload

In an android application I'm loading data from a Db into a TableView inside a Fragment. But when I reload the Fragment it displays the previous data. Can I repopulate the Fragment with current data instead of previous data?
I think you want to refresh the fragment contents upon db update
If so, detach the fragment and reattach it
// Reload current fragment
Fragment frg = null;
frg = getSupportFragmentManager().findFragmentByTag("Your_Fragment_TAG");
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
Your_Fragment_TAG is the name you gave your fragment when you created it
This code is for support library.
If you're not supporting older devices, just use getFragmentManager instead of getSupportFragmentManager
[EDIT]
This method requires the Fragment to have a tag.
In case you don't have it, then #Hammer's method is what you need.
This will refresh current fragment :
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (Build.VERSION.SDK_INT >= 26) {
ft.setReorderingAllowed(false);
}
ft.detach(this).attach(this).commit();
In case you do not have the fragment tag, the following code works well for me.
Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (currentFragment instanceof "NAME OF YOUR FRAGMENT CLASS") {
FragmentTransaction fragTransaction = (getActivity()).getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
}
To refresh the fragment accepted answer will not work on Nougat and above version. To make it work on all os you can do following.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
fragmentManager.beginTransaction().detach(this).commitNow();
fragmentManager.beginTransaction().attach(this).commitNow();
} else {
fragmentManager.beginTransaction().detach(this).attach(this).commit();
}
you can refresh your fragment when it is visible to user,
just add this code into your Fragment this will refresh your fragment when it is visible.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Refresh your fragment here
getFragmentManager().beginTransaction().detach(this).attach(this).commit();
Log.i("IsRefresh", "Yes");
}
}
You cannot reload the fragment while it is attached to an Activity, where you get "Fragment Already Added" exception.
So the fragment has to be first detached from its activity and then attached. All can be done using the fluent api in one line:
getFragmentManager().beginTransaction().detach(this).attach(this).commit();
Update:
This is to incorporate the changes made to API 26 and above:
FragmentTransaction transaction = mActivity.getFragmentManager()
.beginTransaction();
if (Build.VERSION.SDK_INT >= 26) {
transaction.setReorderingAllowed(false);
}
transaction.detach(this).attach
(this).commit();
For more description of the update please see https://stackoverflow.com/a/51327440/4514796
If you are using NavController, try this (kotlin):
val navController = findNavController()
navController.run {
popBackStack()
navigate(R.id.yourFragment)
}
In case you are using Navigation Components
You can use navigate(this_fragment_id) to navigate to this fragment but in a new instance. Also you have to pop the backstack before to remove the actual fragment.
Kotlin
val navController: NavController =
requireActivity().findNavController(R.id.navHostFragment)
navController.run {
popBackStack()
navigate(R.id.this_fragment_id)
}
Java
NavController navController =
requireActivity().findNavController(R.id.navHostFragment);
navController.popBackStack();
navController.navigate(R.id.this_fragment_id);
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);
getSupportFragmentManager().beginTransaction().detach(fragment).attach(fragment).commit();
this will only work if u use FragmentManager to initialize the fragment. If u have it as a <fragment ... /> in XML, it won't call the onCreateView again. Wasted my 30 minutes to figure this out.
Here what i did and it worked for me i use firebase and when user is logIn i wanted to refresh current Fragment first you will need to requer context from activity because fragment dont have a way to get context unless you set it from Activity or context here is the code i used and worked in kotlin language i think you could use the same in java class
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
val context = requireActivity()
if (auth.currentUser != null) {
if (isVisibleToUser){
context.supportFragmentManager.beginTransaction().detach(this).attach(this).commit()
}
}
}
getActivity().getSupportFragmentManager().beginTransaction().replace(GeneralInfo.this.getId(), new GeneralInfo()).commit();
GeneralInfo it's my Fragment class GeneralInfo.java
I put it as a method in the fragment class:
public void Reload(){
getActivity().getSupportFragmentManager().beginTransaction().replace(LogActivity.this.getId(), new LogActivity()).commit();
}
Use a ContentProvider and load you data using a 'CursorLoader'. With this architecture your data will be automatically reloaded on database changes. Use third-party frameworks for your ContentProvider - you don't really want to implement it by yourself...
I had the same issue but none of the above worked for mine. either there was a backstack problem (after loading when user pressed back it would to go the same fragment again) or it didnt call the onCreaetView
finally i did this:
public void transactFragment(Fragment fragment, boolean reload) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
if (reload) {
getSupportFragmentManager().popBackStack();
}
transaction.replace(R.id.main_activity_frame_layout, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
good point is you dont need the tag or id of the fragment either.
if you want to reload
Make use of onResume method... both on the fragment activity and the activity holding the fragment.
For example with TabLayout: just implement OnTabSelectedListener. To reload the page, you may use implement SwipeRefreshLayout.OnRefreshListener i.e. public class YourFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
the onRefresh() method will be #Override from the interface i.e.:
#Override
public void onRefresh() {
loadData();
}
Here's the layout:
<com.google.android.material.tabs.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryLighter"
app:tabGravity="fill"
app:tabIndicatorColor="#color/white"
app:tabMode="fixed"
app:tabSelectedTextColor="#color/colorTextPrimary"
app:tabTextColor="#color/colorTextDisable" />
Code in your activity
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
yourFragment1.onRefresh();
} else if (tab.getPosition() == 1) {
yourFragment2.onRefresh();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
// Reload current fragment
Fragment frag = new Order();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_home, frag).commit();
None of these answers worked for me so I might as well post my solution if anyone still has problems with this. This solution works only if you are using the Navigation component.
Go to your navigation graph and find the fragment you want to refresh. Create an action from that fragment to itself. Now you can call that action inside that fragment like so.
private void refreshFragment(){
// This method refreshes the fragment
NavHostFragment.findNavController(FirstFragment.this)
.navigate(R.id.action_FirstFragment_self);
}
Below code reloads the current fragment onClick of button from Parent Activity.
layoutNews.setOnClickListener(v -> {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, fragNews);
ft.detach(fragNews);
ft.attach(fragNews);
ft.commit();
});
If you are in a fragment then use:
findNavController().run {
popBackStack()
navigate(R.id.your_fragment)
}
Easiest way
make a public static method containing viewpager.setAdapter
make adapter and viewpager static
public static void refreshFragments(){
viewPager.setAdapter(adapter);
}
call anywhere, any activity, any fragment.
MainActivity.refreshFragments();
protected void onResume() {
super.onResume();
viewPagerAdapter.notifyDataSetChanged();
}
Do write viewpagerAdapter.notifyDataSetChanged(); in onResume() in MainActivity.
Good Luck :)

Get the current fragment object

In my main.xml I have
<FrameLayout
android:id="#+id/frameTitle"
android:padding="5dp"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="#drawable/title_bg">
<fragment
android:name="com.fragment.TitleFragment"
android:id="#+id/fragmentTag"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</FrameLayout>
And I'm setting fragment object like this
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment newFragment = new FragmentType1();
fragmentTransaction.replace(R.id.frameTitle, casinodetailFragment, "fragmentTag");
// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
It is setting different types of Fragment objects (FragmentType2,FragmentType3,...) at different time. Now at some point of time I need to identify which object is currently there.
In short I need to do something like this:
Fragment currentFragment = //what is the way to get current fragment object in FrameLayout R.id.frameTitle
I tried the following
TitleFragment titleFragmentById = (TitleFragment) fragmentManager.findFragmentById(R.id.frameTitle);
and
TitleFragment titleFragmentByTag = (TitleFragment) fragmentManager.findFragmentByTag("fragmentTag");
But both the objects (titleFragmentById and titleFragmentByTag ) are null
Did I miss something?
I'm using Compatibility Package, r3 and developing for API level 7.
findFragmentById() and findFragmentByTag() will work if we have set fragment using fragmentTransaction.replace or fragmentTransaction.add, but will return null if we have set the object at xml (like what I have done in my main.xml). I think I'm missing something in my XML files.
Now at some point of time I need to identify which object is currently there
Call findFragmentById() on FragmentManager and determine which fragment is in your R.id.frameTitle container.
If you are using the androidx edition of Fragment — as you should in modern apps — , use getSupportFragmentManager() on your FragmentActivity/AppCompatActivity instead of getFragmentManager()
Try this,
Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
this will give u the current fragment, then you may compare it to the fragment class and do your stuffs.
if (currentFragment instanceof NameOfYourFragmentClass) {
Log.v(TAG, "find the current fragment");
}
I think you can use onAttachFragment event may be useful to catch which fragment is active.
#Override
public void onAttachFragment(Fragment fragment) {
// TODO Auto-generated method stub
super.onAttachFragment(fragment);
Toast.makeText(getApplicationContext(), String.valueOf(fragment.getId()), Toast.LENGTH_SHORT).show();
}
I think you should do:
Fragment currentFragment = fragmentManager.findFragmentByTag("fragmentTag");
The reason is because you set the tag "fragmentTag" to the last fragment you have added (when you called replace).
You can get the list of the fragments and look to the last one.
FragmentManager fm = getSupportFragmentManager();
List<Fragment> fragments = fm.getFragments();
Fragment lastFragment = fragments.get(fragments.size() - 1);
But sometimes (when you navigate back) list size remains same but some of the last elements are null. So in the list I iterated to the last not null fragment and used it.
FragmentManager fm = getSupportFragmentManager();
if (fm != null) {
List<Fragment> fragments = fm.getFragments();
if (fragments != null) {
for(int i = fragments.size() - 1; i >= 0; i--){
Fragment fragment = fragments.get(i);
if(fragment != null) {
// found the current fragment
// if you want to check for specific fragment class
if(fragment instanceof YourFragmentClass) {
// do something
}
break;
}
}
}
}
This is the simplest solution and work for me.
1.) you add your fragment
ft.replace(R.id.container_layout, fragment_name, "fragment_tag").commit();
2.)
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment currentFragment = fragmentManager.findFragmentById(R.id.container_layout);
if(currentFragment.getTag().equals("fragment_tag"))
{
//Do something
}
else
{
//Do something
}
It might be late but I hope it helps someone else, also #CommonsWare has posted the correct answer.
FragmentManager fm = getSupportFragmentManager();
Fragment fragment_byID = fm.findFragmentById(R.id.fragment_id);
//OR
Fragment fragment_byTag = fm.findFragmentByTag("fragment_tag");
Maybe the simplest way is:
public MyFragment getVisibleFragment(){
FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for(Fragment fragment : fragments){
if(fragment != null && fragment.getUserVisibleHint())
return (MyFragment)fragment;
}
return null;
}
It worked for me
You can create field in your parent Activity Class:
public class MainActivity extends AppCompatActivity {
public Fragment fr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
And then inside each fragment class:
public class SomeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
((MainActivity) getActivity()).fr = this;
}
Your 'fr' field is current fragment Object
It's working also with popBackStack()
I know it's been a while, but I'll this here in case it helps someone out.
The right answer by far is (and the selected one) the one from CommonsWare. I was having the same problem as posted, the following
MyFragmentClass fragmentList =
(MyFragmentClass) getSupportFragmentManager().findFragmentById(R.id.fragementID);
kept on returning null. My mistake was really silly, in my xml file:
<fragment
android:tag="#+id/fragementID"
android:name="com.sf.lidgit_android.content.MyFragmentClass"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
The mistake was that I had android:tag INSTEAD OF android:id.
Do a check (which fragment in the activity container) in the onStart method;
#Override
protected void onStart() {
super.onStart();
Fragment fragmentCurrent = getSupportFragmentManager.findFragmentById(R.id.constraintLayout___activity_main___container);
}
Some check:
if (fragmentCurrent instanceof MenuFragment)
#Hammer response worked for me, im using to control a floating action button
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
android.app.Fragment currentFragment = getFragmentManager().findFragmentById(R.id.content_frame);
Log.d("VIE",String.valueOf(currentFragment));
if (currentFragment instanceof PerfilFragment) {
PerfilEdit(view, fab);
}
}
});
If you are extending from AbstractActivity, you could use the getFragments() method:
for (Fragment f : getFragments()) {
if (f instanceof YourClass) {
// do stuff here
}
}
If you are defining the fragment in the activity's XML layour then in the Activity make sure you call setContentView() before calling findFragmentById().
If you are using the BackStack...and ONLY if you are using the back stack, then try this:
rivate Fragment returnToPreviousFragment() {
FragmentManager fm = getSupportFragmentManager();
Fragment topFrag = null;
int idx = fm.getBackStackEntryCount();
if (idx > 1) {
BackStackEntry entry = fm.getBackStackEntryAt(idx - 2);
topFrag = fm.findFragmentByTag(entry.getName());
}
fm.popBackStack();
return topFrag;
}
This will give you the current fragment class name -->
String fr_name = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
you can check which fragment is currently loaded by this
supportFragmentManager.addOnBackStackChangedListener {
val myFragment = supportFragmentManager.fragments.last()
if (null != myFragment && myFragment is HomeFragment) {
//HomeFragment is visible or currently loaded
} else {
//your code
}
}
I use the following function in Kotlin:
supportFragmentManager.fragments.run {
getOrNull(size - 1)?.let { currentFragment ->
...
}
}
I recently worked on an activity involving multiple fragments so thought to share the method I used here:
Firstly, I declared a function getCurrentFragment() which returned me, yeah you guessed it, the current fragment, lol.
private fun getCurrentFragment(): Fragment? {
return supportFragmentManager.findFragmentById(R.id.fragmentContainerView)
}
Then I override the onBackPressed function in the activity to define the navigation within fragments. Suppose, I wanted to show fragment 2 if user is in fragment 3 and presses back so I did something like this to achieve this
override fun onBackPressed() {
if (getCurrentFragment() is Fragment3) {
showFragment2()
} else {
super.onBackPressed()
}
}
And in showFragment2() I did something like this:
private fun showFragment2() {
val fragment = Fragment2.newInstance()
supportFragmentManager.commit {
replace(R.id.FragmentContainerView, fragment, "Add a tag here")
}
}
I think this should give better idea to people looking on how to navigate through fragments within an activity.

Categories

Resources