How to reuse fragment's view for a new fragment - android

I need to update a fragment with a different views.
As I figured out, to force Fragment::onCreateView() method call (to show my updates to the user) I can only use FragmentTransaction's method replace(, ).
It works good if I create a new Fragment and a new view for returning it from onCreateView() method every time I call FragmentTransaction::replace().
But I wish to keep some views in memory.
How can I reuse my views?
The problem is that if I use my view (that was attached to already replaced fragment) at a new fragment, I get an exception:
"java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first."
So, I try to detach the view from fragment by calling FragmentTransaction.detach() or FragmentTransaction.remove() to cause removing fragment from the activity and my view from already replaced fragment, but it doesn't help.
Does anybody know how to force a fragment to remove its child view (that was returned inside onCreateView()?

You're better off keeping the view contained within the Fragment so the Fragment itself handles it appropriately. Either have viewless Fragments send data to that Fragment to update the View or build the View with the parameters. It's cleaner and in the long run, much more maintainable.
Check out the Adding a Fragment without UI section.

Related

Android Development - Find Text View Inside of a fragment that's inside of a TabLayout

I realize views cannot be "found" if they're not a direct child of the layout you're looking from. I have an Activity, which has a ViewPager inside of it. The 0th tab or view inside of the ViewPager has a my_fragment.xml inflated in it. That fragment then has a TextView inside of it. How can i access it from my main/root activity. Also, in the onCreate method of the fragment i've put a line of code that just calls setText on the TextView, and that doesn't seem to be called at all. Any ideas on all of this?
To access a view you need not access every parent / super parent of it. The parent or any other parent up in the view hierarchy is enough. If you get the reference to any parent/super parent of the child view, you can call View.findViewById() to get the child.
View.findViewById() - Look for a child view with the given id. If this view has the given id, return this view.
Don't try to setText in the onCreate of Fragment. You need to do this after the fragment inflates the view. This happens only in the onCreateView. So you need to do the setText in the onCreateView method or in any other method after this one in the lifecycle (preferably onActivityCreated()).
To access the fragment class instance itself from the activity, you can refer this: Is it possible to access the current Fragment being viewed by a ViewPager?

Is Using a 'Root' Fragment A Better Way Replace Fragments in ViewPager?

Replacing Fragments in ViewPager is a question that has been asked many times but most answers are hacks, broken/not complete or quite old. This example is working really well - https://github.com/danilao/fragments-viewpager-example but it actually uses an empty root fragment and adds the real fragment on createView.
Is there any other better way to avoid having to use a root frame?
The correct approach would be to override your PagerAdapter's getItemPosition() to update your PagerAdapter with the new Fragment:
Called when the host view is attempting to determine if an item's position has changed. Returns POSITION_UNCHANGED if the position of the given item has not changed or POSITION_NONE if the item is no longer present in the adapter.
The default implementation assumes that items will never change position and always returns POSITION_UNCHANGED.
In this case, pages that haven't changed return PagerAdapter.POSITION_UNCHANGED, the Fragment that is removed returns PagerAdapter.POSITION_NONE, and the new Fragment gets its new position.
You'll change the underlying data in your PagerAdapter, then call notifyDataSetChanged(). This is what triggers the ViewPager to call getItemPosition() for each visible Fragment, replacing or moving them as needed.
Your example uses the right technique (child fragments inside root fragment) but the wrong way: for managing child fragments inside the root fragment, it must use the child fragment manager using getChildFragmentManager().

Difference between getActivity() and view in Fragment

What is the difference between
getActivity().findViewById(...)
and
View view = inflater.inflate(R.layout.fragment_fragment_v, null);
view.findViewById(...)
in Fragment (when converting Activity to Fragment)?
The difference is that with getActivty.findViewById(...) you are finding views in the scope of activity (activity's layout). With iflater.inflate(R.layout.fragment_fragment_v, null); view.findViewById(...) you are inflating the layout of your fragment and then finding view's in that layout.
But since your fragment is attached to the activity, you will find the view bothways, but I suggest you are finding view's for your fragment in your fragment's scope since there may be several fragments that have common layouts meaning there may be several view's associated with the same ID and that makes the getActivity().findBiewById(...) method unreliable
When you call findViewById with getActivity() you are telling Android to find the View within the Activity's layout, since Fragments are hosted inside Activities it will return you the correct View if its in the hierarchy.
By calling findViewById with the inflated View or in fact the getView() method provided by the framework you are essentially telling Android to find that View within the Fragment's view hierarchy, this should be your preferred approach as the findViewById algorithm will have to look for your View from a lesser set of View's and hence the search will be faster.
I'll leave you with this explanation about getView() from the developer docs.
getView()
Get the root view for the fragment's layout (the one returned by onCreateView(LayoutInflater, ViewGroup, Bundle)), if provided.

When are views attached and detached?

This question is not about how to detect if a view is attached or detached.
In general, when is a view attached or detached? Is there a lifecycle diagram for this?
To clarify, I'm looking for answers to what happens when: Activity sent to background, opaque view placed on top, visibility set to GONE, view inflated, parent detached, etc. This is not an exhaustive list - I just want to understand how attaching and detaching of views works, at a fundamental level.
Update with more examples of what I'm trying to get at:
What about fragments vs. activities?
What about nested views - in what order are views attached/detached (parent->child or child->parent)?
Are views measured before they are attached or after?
What about using addView() to a ViewGroup manually?
Edit: Summary:
For Activities, views are attached in setContentView(). Views are detached in onDestroy() or when setContentView() is called with a different view.
For Fragments, views are attached after onViewCreated() finishes, and are detached after onDestroyView() finishes.
For ViewGroups, views are attached in addView() and detached in removeView()
setVisibility() does not affect the attached state of a view
From the official documentation:
An activity is a single, focused thing that the user can do. Almost
all activities interact with the user...
The first thing that needs to be noted is that it is not a must for activities to be associated with a layout. You can have an activity with no UI (and hence no View). Android even specifies a no UI theme for this.
Moving on to your question - a View gets attached to an Activity at the moment you call setContentView(view). This is usually called within the onCreate() method. The reason you usually have this in the onCreate() method is because most of the initialization is done there. And how could you initialize your widgets if the view has not been inflated and attached to the Activity? Hence, if you have a view, you almost invariable end up calling setContentView() inside your onCreate() method preceding all other initialization.
But does that mean that the view (if it exists) must be tied to the
activity only within the onCreate() method?
To answer this question, let's see what the lifecycle of an Activity looks like. You start your app:
onCreate() -> onStart() -> onResume() // They get called consecutively
The stage you are now in is where all the widgets have been initialized.
So why not inflate and attach the activity in onResume() and do all the
initializations there?
Of course, you could. But imagine what happens when a dialog (a partially opaque view) shows up? The Activity is now partially covered and is in the background. The onPause() method is called. The layout is still attached to the Activity at this point. You take some action and dismiss the dialog. onResume() gets called. The layout would be inflated again. All the initializations would happen again and you would lose your state. Even if you did not have much in the way of initialization, you would still be making a pretty expensive call by calling onCreate() again. And you want to avoid this in resource limited mobile devices.
What happens when an opaque view comes up and the Activity is now in
the background but still running (like an incoming phone call or opening another activity)?
Now the following callbacks happen:
onPause() -> onStop()
When you move back to the original activity
onRestart() -> onStart() -> onResume()
For the same reason as I mentioned in onPause() you do not want to inflate and attach a layout here.
But what happens to the layout itself when an Activity is in the
background. Is the layout still attached?
Yes, it very much is. If another activity comes up which uses the same layout as the original activity, then the new activity has it's own layout and there is no sharing of layouts.
What happens if the user terminates the activity by pressing the Back
button?
Assuming the onBackPressed() method is not overridden to achieve custom behavior (in which case, it is up for grabs), onDestroy() is called and the activity is destroyed and there is no View associated with it anymore.
What happens when the activity is in the background and the Android GC
decides to destroy the activity and reclaim resources?
According to the activity lifecycle within the documentation, onDestroy() will be called. But there is no guarantee of this. At this point, the activity and it's associated view are simply garbage collected and there is no connection.The next time you start the app, onCreate() will be called as usual and you simply start from the beginning again.
What happens when I rotate my device?
The way Android works is to actually destroy the current activity and inflate the new layout again and start from the onCreate() method again. So what technically happens is:
onPause() -> onStop() -> onDestroy() -> onCreate() -> onStart() ->
onResume()
Because of this, you can even have a different layout and view while in landscape mode.
EDIT: Added the relationship between activities, fragments and views
A fragment represents a portion (or behavior) on the screen. A fragment can be made to occupy the full screen or you can have multiple fragments within an Activity. Fragments have their own life cycle but it is closely tied to the host activity's life cycle (and beyond the scope of this answer). Since we are specifically talking about views, I will limit this answer to two methods of interest:
onCreateView()
onViewCreated()
The methods are called in the following order:
onAttach() -> onCreate() -> onCreateView() -> onViewCreated()
You do the actual layout inflation within the onCreateView() and then you do the initializations within the onViewCreated() method. The result of the onCreateView() method is used by Android to inflate the view.
So when is the fragment created in the first place by the Activity?
There are two ways to display fragments - one is to put them within the xml layout of the activity (just like any regular widget where instead of the widget name, you will be using the fully qualified package name of the fragment class) or you can do the addition using FragmentManager programmatically (which is the preferred method).
If you were defining the fragment within the xml layout, you should know that the fragment cannot be removed programmatically. It would be hard to modify this and reuse that screen space for other fragments. Also in this case, the view is attached and tied to the activity. In this case, you will inflate the xml layout of the Activity within the onCreate() method of the activity. So now, the flow will looks something like:
onCreate() [Activity] -> onAttach() [Fragment] -> onCreate()
[Fragment] -> onCreateView() [Fragment] -> onViewCreated() [Fragment]
-> onStart() [Activity] -> onResume() [Activity] -> onActivityCreated() [Fragment]
So first the fragment view is instantiated and attached to the fragment before the onStart() method of the activity is created.
If the fragment is added programmatically, if it is added within the onCreate() method, then it follows the same flow. It can be started anywhere. You simply have to substitute the life cycle of the fragment within the activity in the appropriate place. When you add fragments programmatically, while the fragment is hosted in the activity, the view is attached to the activity. When the fragment is removed from the activity, onDetach() is called and the view is no longer a part of the Activity. The resources taken by the fragment can be released.
What about Nested Views, Nested Fragments, etc.?
In nested views, like one layout container inside another, the rules of the parent container apply to the immediate child container. Always the parent gets initialized first. So for a widget inside a LinearLayout, the parent LinearLayout is constructed first immediately followed by the child. When destroying such views, everything goes when the parent ceases to exist. I have not read about any documentation as to an order in which this may happen. The Android GC may have rules but I am not sure if they are documented anywhere.
You can have nested fragments too - in this case, the parent fragment gets initialized before the child fragment does (and it makes sense doesn't it?). When a parent fragment ceases to exist, the child will also cease to exist. The child cannot exist without the parent but you can have the parent without the child.
The bottom line for nested views is that once the parent view is
destroyed, it takes the child view immediately with it.
Are views measured before they are attached or after?
Views are measure after they are attached. Calling getMeausredWidth() or getMeasuredHeight() will return zero prior to this. But what you can do is call neasure() directly on the view before it is attached and pass MeasureSpecs (I would suggest you read up more on this in the official docs) to set some constraints. But this option is not fool proof as it depends on the parent ViewGroup enforcing it's own constraints which take higher precedence. To simply answer your question, views are measured after they are attached.
What about using addView() to add a view to a ViewGroup manually?
This is simply the same as nested views. The child exist only when they are added and this is controlled by the user. In nested views defined in layout xml, the children are inflated immediately after their parent. Here the control is more in the hands of the user. When the parent view in this case is destroyed, it takes the child view with it.
As a last point, I'd also like to mention that you should not use static handles for views as this would lead to a lot of headaches with the tearing down of views.

Fragment basics

I am working on a application for which I have some issues with fragments. First of all , I want to know if it is possible to make one fragment inside another fragment. And the second one is when to call onCreateView() and onActivityCreated() and which is best?
Per the Android sources:
onCreateView is called by the Activity during the construction of the view hierarchy. This is where the Fragment has the opportunity to instantiate its own user interface view.
onActivityCreated is called when the Activity has been fully created and finished instantiating the view hierarchy. At this point it's safe for the Fragment to access the its views and restore itself from some saved state.
You cannot create a fragment inside another fragment. You should communicate between fragments thru activity.See http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
I didn't understand your second question clearly. But I generally leave onActivityCreated() blank without changing it. And use onCreateView() in a similar way with onCreate().

Categories

Resources