Closing FrameLayout for a Fragment in Android App - android

I'm working on a simple Android App as a self-learning Project. I've got a lot of it functioning, and I have a main Activity which has a FrameLayout and some RecyclerView and FloatingActionButton stuff going on inside of it.
However, I want to make one of my buttons in my NavigationDrawer open a different view in the FrameLayout using Fragments. Is there a way to do this, sort of making a new Fragment for the RecyclerView and the other stuff and putting the RecyclerView and FloatingActionButton in there?
I tried doing something like this (when the appropriate NavigationDrawer button was clicked):
statsFragment = new StatsFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.rootLayout, statsFragment);
transaction.addToBackStack(null);
transaction.commit();
But this caused my app to crash. Any pointers?

Is your R.id.rootLayout a Layout or a Fragment component?
If your main Activity has a hard coded Fragment (by hard coded i mean declared in your XML), then no, you can't change a hard-coded fragment content with FragmentTransaction.
More information on this question's answer.
Finally, you can't put your components from one Activity inside a new Fragment/Activity since each component belongs to one and only one Context.
See, Activity extends Context. When you get a reference to a component declared in your XML by using Activity.findViewById(int), you are actually making a pointer to a determined View from this Activity's layout, defined in your onCreatemethod with setContentView(id). You can't take this pointer and throw it to another Fragment or Activity within your application without expecting any problems. (Well, maybe you can, but it's totally against the best practices of Android Programming).

Related

Which Layout to use with Fragments?

Recently delve into fragments and from what I understand to create a fragment you need a java class and the fragments layout. This makes sense. However what I cant seem to wrap my head around is what "container", or layout do I use to store/insert the fragment? In android studio you can use this to insert fragments, or you can use any other of the layouts. But which one is ideal to use?
Also I saw in a reddit post that I shouldn't be using fragments at all and that its preferred to instead use Frame layouts and play around with your views visibility for the desired effects. Is this true?
You're slightly over-complicating the concept of Fragments.
Fragments, like Activities, don't actually need a dedicated fragments layout xml file. If you choose to do so, you can create the entire layout through Java code, not that I will understand why you'll choose to do so.
So for Fragments, you don't need a Java class and a fragment's layout file. The only requirement is the Java class, and the layouts file is just the preferred approach to inflating a layout, similar to how it is for Activities.
As for your question about the container of the fragments, it's really a matter of your app's design.
You can add a Fragment to your Activity or other Fragments, through the FragmentManager in code or through the <fragment> tag in your layout.xml files.
Neither of those are the best way or the preferred way, since it really depends on what your app needs.
Using the <fragment> tag will cause that fragment to always be added whenever the layout is inflated. This is actually VERY bad if your Activity requires dynamically switching Fragments due to your use of things like ViewPagers, Tabs, Drawer Navigation, or etc. However, it's GREAT if there's no need to dynamically switch fragments and for that specific Activity or parent Fragment, this fragment is a fragment that's always loaded.
For example, let's say you designed a flexible AddNew Fragment that's used in a Dialog and an AddNewActivity. Due to reusing the same screen and code, you decide to make this part of your code a fragment so you can insert it inside a DialogFragment or into another Activity. But, for those DialogFragments and Activities, the only Fragment it'll have is the AddNewFragment, so it'll make sense to just insert that fragment into the Dialog layout and Activity layout through the <fragment> tag.
As for the option with Java code, the preferred approach is to use a FrameLayout. But there's no need to play around with any View visibilities!
The common approach is to just use:
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
A FrameLayout is used because it's going to be the container of the Fragment. In other words, the Fragment will be stored inside of this layout.
So in Java code, you can simply use this code to replace the Fragment inside the container with your new one:
getSupportFragmentManager().beginTransaction().replace(R.id.container, AddNewFragment.newInstance()).commit();
Optionally, you can use add() instead of replace() if you want the fragment to be placed ontop of another fragment within the FrameLayout container.
So yes, to give a decisive answer to your question, there's no ideal way to add a Fragment to an Activity or another Fragment. Each option has it's benefits and drawbacks, with some working better for certain situations and others working better for others.
In the end, it really depends on what your App needs. If you need your Fragments to be flexible, so you can switch Fragments, then this must be done through Java code, because fragments added through the <fragment> tag can't be removed at runtime. However, if you don't need your Fragment to be replaced and it's definitely always going to be showing the same Fragment, then using the <fragment> tag removes the need to write extra Java code to load the dedicated Fragment.
One thing I really do need to point out is... that reddit page you read about is wrong. The 'preferred' way to use Fragments is not to use FrameLayouts and play around with View visibilities. I actually have no idea why there's even a need to change View visibilities.
You can use the new androidx.fragment.app.FragmentContainerView to get a better performance than FrameLayout.
Here more information.
You could use the Fragment layout, but this isn't very flexible. If you're just showing one Fragment, it should work, but using a FrameLayout and inserting your Fragment into it works better as this allows you to change them on the fly.
You may see a FrameLayout with the id R.id.container or something similar, and what this is used for is the Transaction.
For example, if you want to insert FragmentOne into your layout, you can just do this and it'll put it into R.id.container.
Fragment fragment = new FragmentOne();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.commit();

Does adding fragments with tags cause them to not be destroyed when their parent is destroyed?

I have an android application that uses one activity and a number of fragments to build a ui dynamically
The base activity has a simple LinearLayout in it that has nothing (BaseActivity)
I add a fragment to it that only contains a drawer layout with an actionbar a framelayout and a navigation bar (BaseFragment)
To that I add one of two fragments, one shows all children as lists (SerialFragment) , the other in a wizard style (WizardFragment)
Each of those can add one (in case of a wizard) or many (in case of a list) fragments (QuestionFragment)
When I navigate away from BaseActivity then the BaseFragment's onDestroy() gets called, but not the onDestroy() of any of the child fragments
I add the child fragments like so
FragmentTransaction trans = parent.getFragmentManager().beginTransaction();
set_default_animation(trans); //this just adds a custom animation
trans.replace(R.id.wizard_content, QuestionFragment.NewInstance(),question_id.toString()); //in case of a wizard
trans.add(R.id.list_content,QuestionFragment.NewInstance(), question_id.toString());//in case of a list
trans.commit();
The only difference between the BaseFragment (which gets destroyed) and the others, is that in the others I add a tag to them (section_id or question_id) so that I can retrieve them using findFragmentByTag.
Yet when the user navigates away from the activity only BaseFragment's onDestroy() is called.
Is the reason for this the fact that , that fragment is the only one I haven't added using a tag?
Note that I am not using a support fragment manager, the normal one, so I use tags to locate the fragments I want , since the non-support fragment manager does not contain getFragments().
Also note that I have not set the retain instance flag to true on any of the above mentioned fragments
I could test the above by removing tags and adding references to the fragments on the parents, but that means a LOT of refactoring which I would like to avoid if that is not the problem.
Thanks in advance for any help you can provide
After refactoring everything, it seems that the tags weren't the problem (though I still removed them)
What fixed it for me, is using getChildFragmentManager() instead of getFragmentManager() to update the gui
That way when the base view gets destroyed its children are removed aswell
Hope it helps someone

Show nested fragment on screen rotation without showing parent fragment

When rotating the screen my nested fragment is shown but for some brief moments, the parent fragment is also shown.
I have my MainActivity that has a FrameLayout with ID activity_base_container.
I'm doing this when my activity starts:
Fragment initialFragment = getInitialFragment();
mFragmentManager.beginTransaction()
.add(R.id.activity_base_container, initialFragment, initialFragment.getClass().getSimpleName())
.commit();
That initialFragment initial fragment is responsible to check some conditions and depending them will launch one of two possible fragments:
fragmentManager.beginTransaction().replace(R.id.activity_base_container, fragment, fragment.getClass().getSimpleName()).commit();
Lets assume it launches FragmentF (whit a root FrameLayout with id fragment_f_root). This fragments layout has a set of options. When the user clicks one of those options, the corresponding fragment is created and is launched like this:
//The example here is an option that displays a google map.
fragment = FragmentMapMultipleActivity.newInstance();
fragmentManager.beginTransaction()
.replace(R.id.fragment_f_root, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
At this point all is working as expected. The problem is when I rotate the screen. FragmentF appears briefly and then immediately FragmentMapMultipleActivity, the nested fragment, appears.
Is it possible after rotating the screen show only the nested fragment or I should change my "architecture" to something else?
should change my "architecture" to something else?
Probably, you should.
The brightest Android-minds from Square are even advocating to avoid simple fragments everywhere it's possible: Advocating Against Android Fragments
Nested fragemnts, in its turn, increase complexity exponentially. The only good pattern of using them I've seen so far is ViewPager with it's FragmentPagerAdapter. In majority of other cases, consider using Custom Views instead.
It keeps your app's lifecycle cleaner and more predictable.
I don't think you can do much with this blinking you see, apart from:
setRetainInstance(true) and avoid full re-creation of the Fragment in Activity, so you keep you fragment's data during change of the configuration (and then pass same retained fragment to the fragment manager)
keeping layouts as lightweight as possible
avoid re-creation of already initialized variables
keep onViewCreate() as lightweight as possible
Good luck!

Android How to retain generated view ID for dynamically created fragments through rotation

I'm creating FrameLayouts and Fragments at runtime. I have a LinearLayout (R.id.presentationRight) in my xml file. Every time I need a new fragment within that layout, I do the following.
Create a new FrameLayout and add it to the LinearLayout
Generate an ID for the FrameLayout so FragmentTransaction can reference it
Create a new Fragment
Perform a FragmentTransaction to place the new Fragment in the new frame.
The code looks like this
LinearLayout presentationRight = (LinearLayout) findViewById(R.id.presentationRight);
FrameLayout bluRayFrame = new FrameLayout(MainActivity.this);
bluRayFrame.setId(View.generateViewId());
presentationRight.addView(bluRayFrame);
BluRayFragment bluRayFragment = new BluRayFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(bluRayFrame.getId(), bluRayFragment);
fragmentTransaction.commit();
It works perfectly. I can run as many copies of this method as I want and it always adds another instance of this fragment to the LinearLayout, which is exactly what I want.
The problem comes when the screen rotates. When I had a single existing frame in the layout and I was just replacing the existing frame, rotation worked perfectly. You could view the app in portrait or landscape and it always reloaded the fragment perfectly. However, now that the framelayout I'm addressing isn't actually in the XML file, it crashes the app and gives me a null pointer within the Fragment itself when it tries to reference container.getContext(). I'm assuming that since the Fragment isn't actually tied to the xml file that when the Activity reloads on rotate, the container isn't there so the context isn't there, but I don't know how to fix it.
I'm not doing anything special to handle the rotation right now, just letting the activity do everything on it's own.
Thoughts? I'd really like to avoid creating a bunch of framelayouts in code and referencing them individually because i don't know how many of these fragments will eventually be necessary, so writing it open ended seems like the best way to handle things if I can figure out how.

Android replace fragment or launch new activity with fragment

I am still unsure of best design practices using fragments. I've looked at the dev docs at:
http://developer.android.com/guide/components/fragments.html
There seems to be two ways that a new screen can be made, in a single pane layout at least. Let's say I have a button inside one fragment and I want it to show a new view when clicked. Should I be using the original activity and replace with a FragmentTransaction or should I have the original activity launch an intent to a new activity that displays that fragment. I am pretty sure both can work. I'm more wondering about design practice. Or should I use a dialogfragment?
If it matters, the second fragment needs to pass information back to the original fragment at some point.
If all you need to do is return some data to the fragment I would probably use Dialog.
However, for switching fragments, its much better to use a FragmentTransaction to change Fragments, that way you don't need a new Activity (one of the main positives of using Fragments).

Categories

Resources