onCreateView | Techbirds
I was finding it tough to work with Fragments in my recent works I managed to run one sample thoroughly great thanks to Vogella Tutorials, which helped me to figure out the scene behind the mirror.
How to do this
- In one activity we can display two fragments both for handset and tablet devices.
- for Tablets:
- use one Activity to display both fragments.
we use same activity as used by tablet activity but use different layout that contains only one fragment and when required another activity we will start new activity with another fragment layout.
Among both approaches we prefer the 2nd one since its flexible approach. In this the mainActivity checks if the layout contains the detail fragment if yes it updates it else it starts another activity for details.
- Extend it with android.app.Fragment class or any of its subclasses.
- Adding fragment statically in layout file. to check if its present or not in layout
DetailFragment fragment = (DetailFragment) getFragmentMAnager().findFragmentById(R.id.frament_detail); if(fragment==null || !fragment.isInLayout()) // start new activity else fragment.update()
DetailFragment fragment = (DetailFragment) getFragmentMAnager().findFragmentById(R.id.frament_detail);
if(fragment==null || !fragment.isInLayout())
// start new activity
Oncreate —> called after activities Oncreate
—> before onCreateView
OnCreateView –> returns View object here we use Inflater object to inflate XML layout view.
–> don’t need this for headless fragments.
onStart –> called when fragment is visible.
Communicating between fragments and activities.
Important :- the fragment should not directly interact with activity to increase the reuse.
For this, every fragment should define a inner interface that must be implemented by activity using fragment. and this is checked in onAttached() method of fragment, since its the first method to be called in Lifecycle.
- Fragment can be easily reused in activities and layouts
- It runs in context of activity, but implements its own Lifecycle and UI
- Fragments can also be without fagments known as headless fragments.
- Can be added to activity statically or dynamically
- If fragment is added in layout file it cannot be removed during runtime
- Fragments don’t subclass Context, so we call getActivity() method to get parent activity’s reference.
- setRetainState() vs addToBackStack()
- add animation using setCustomAnimations() or setTransition() using constants starting with FragmentTransaction.TRANSIT_FRAGMENT_*****.
You can Download the example here.
- Vogella Tutorials
- Android Fragments
659 total views, 1 views today
Tags: Fragment Lifecycle, Fragments, Fragments Example, Fragments Sample, onAttached, onCreateView