Fragment without activity - android

I have been asked an interview question: Can a fragment exist without activity? I searched for answers but didn't get a proper answer and explanation. Can someone help?

Yes, you can do this anywhere:
new YourFragment();
As fragments must have a parameter-less constructor.
However its lifecycle doesn't kick in until it is attached. So onAttach, onCreate, onCreateView, etc. are only called when it is attached. So most fragments do nothing until they are attached.

It can exist as an object in memory (by creating it with new), but it needs to be attached to an Activity in order to appear on the screen, assuming it has any UI (fragments don't have to have UI).

A Fragment can exist independently, but in order to display it, you need the help of an Activity. The Activity will act like a container for the Fragment(s).

A fragment is not required to be a part of the Activity layout; you may also use a fragment without its own UI as an invisible worker for the Activity but it needs to be attached to an Activity in order to appear on the screen.

As soon as you create an instance of the Fragment class, it exists, but in order for it to appear on the UI, you must attach that fragment to an activity because a fragment's lifecycle runs parallel to an activity's lifecycle. Without any call to Activity's onCreate(), there will be no call for onAttach(), onCreate(), onCreateView() and onActivityCreated() of fragment and so it can't be started.

I read above top rated answer , i am not disagreeing but android already provides to make independent fragment without activity DialogFragment , which extends fragment . if you want show in full screen first extends DialogFragment then
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_FRAME, android.R.style.Theme_Holo_Light);
}

Android app must have an Activity or FragmentActivity that handles the fragment.
Fragment can't be initiated without Activity or FragmentActivity.

Related

Are Activity faster to create than fragment?

I had a layout for Fragment to show information about a product but sadly, during the creation of fragment there was slight lag( glitch) of around 50ms (that is what I guess how log the lag is which is a lot as the refresh rate for android is 16ms) but when I use the same layout in Activity directly and applied the same logic it looked and felt smooth.
Are there any particular reasons for this case ?
Are there any way to make fragment look as smooth as activity during creation ?
You can test some complex layout and try inflate it as fragment's view and using same as layout content for activity.
This is how my oncreate looks like in both fragment and activity:
#Override
public void onCreate ( Bundle savedInstanceState ) { // or equivalent override for fragment.
super.onCreate ( savedInstanceState );
setContentView ( R.layout.fragment_product_profile );
initLayout ();
loadData ();
initCustomMadeImageSlider ();
autoScrollViewPager ();
}
A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle.
Fragment : Major Advantage is
A separate Activity is created for each form factor with the non-UI
details duplicated or otherwise shared across each Activity
Fragments eliminate this problem by taking on the UI details and leaving the other responsibilities to the Activity. This way a separate Fragment can be created for each form factor with the form factor specific UI details being the only responsibilities of each Fragment.
Are Activity faster to create than fragment ? YES . Activity->Fragment .
A Fragment represents a behavior or a portion of user interface in an
Activity
Please read about When to use Fragments vs Activities

Update Activity title from fragment in FragmentPagerAdapter

I have v4.ViewPager inside Activity and use SlidingTabLayout from google's examples SlidingTabBasics. The problem I encounter is that each fragment retrieved from getItem(position) in v4.FragmentPagerAdapter has to refresh activity title. I have already learnt the hard way that FragmentPagerAdapter causes fragments to have really weird life callbacks so I can't probably use onResume or onStart. I noticed though that onCreateOptionsMenu(menu,inflater) gets called exactly when I want to refresh activity title. Is there a callback to supply actions when ViewPager has settled the fragment and it should change activity title?
Setting callback on ViewPager.onPageSelected(position) is inconvenient because I want this information to be propagated from fragment, not to fragment.
Currently I 'steal' onCreateOptionsMenu(menu,inflater) to do the work for me but it causes optimisation issues when no menu should be inflated but I still want the fragment to be able to affect activity title.
Have you tried this code in your fragment:
if(getActivity() != null){
getActivity().setTitle("new title");
}
Take into consideration that getActivity() will be null if the fragment is not yet attached to the activity.
Godspeed.
You can do this in different ways.
You can use interfaces in fragments that can be implemented by activity. But the drawback is, if you do have large number of fragments you must implement all of them.

Android manage fragment circles

I am using Fragments in a FragmentActivity with a FragmentManager.
I need to keep the last modifications in the fragment.
If I use FragmentTransaction.replace(); It will destroy the Fragment and reset it.
I decided to hide the previous Fragment and show the next one.
But the Fragment can be destroyed by an income call or a device rotation and they can't be shown anymore.
My question is how can I manage this?
If I use show(), hide() I need to forbid the fragment's destruction
If I use fragmentTransaction.replace() I need to save the last state.
The second solution looks better but I have no idea how to proceed.
Are there any other solutions?
Ok I fixed it.
THe trick is to use FragmentTransition.replace() and FragmentTransition.addTobackStack(null);
And overide onBackPressed of the activity like this:
#Override
public void onBackPressed()
{
}
Hope it will help!

How to make call backs between Fragments of the same Ativity

I have 4 tabs in an Activity.
Each of them is a Fragment. And every Fragment has a ListView.
So, if i change the ListView in Fragment, it must change the ListView in all other Fragments ie.., Tabs.
The problem i face is while creating the interface instance.
It takes it's own onClick() method.
In case i want a callback to the parent activity i could have done that by overriding onAttach. But how to make a callback to a Fragment?
From Developers site:
Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
So, make a callback to the Activity which in turn makes a callback to other fragments??
Thank You
It's pretty simple,all You need is steps below:
1) From onClick method in your first fragment make a function call of activity:
((IYourActivityInterface) getActivty()).activityMethod();
2) In your activity find fragment by tag or id and run it's method:
public void activityMethod(){
Fragment tabFragment = getFragmentManager().findFragmentByTag("second_fragment");
// or Fragment tabFragment = getFragmentManager().findFragmentById(R.id.frag);
if (tabFragment!=null){
((IFragmentInterface) tabFragment).fragmentMethod();
}
}
Hope this is what you are looking for.)

Is there a way for an Activity to know what fragment was just created?

An Activity may inflate an arbitrary layout xml that may or may not have a Fragment placeholder in it.
If it does , the Fragment will be instantiated and attached to the Activity.
Is there any way to get a reference to the Fragment from the Activity that has been attached to it ?
FragmentManger.findFragmentById() assumes you know the ID in advance to make it work but in this situation I am proposing, it is not available.
The behavior I'd ideally like to have is that the Activity is aware of any Fragments attaching itself to it so that it may respond to it.
Whenever a fragment is attached to an activity the following callback method is called with the fragment attached as the parameter, you can use it store the reference.
onAttachFragment(Fragment fragment)
http://developer.android.com/reference/android/app/Activity.html#onAttachFragment(android.app.Fragment)

Categories

Resources