onAttached | 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

  1. In one activity we can display two fragments both for handset and tablet devices.
  2. for Tablets:
    1. use one Activity to display both fragments.

For Handsets:
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.

Defining Fragments

  1. Extend it with android.app.Fragment class or any of its subclasses.
  2. 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

else

fragment.update()

LifeCycle

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.

Conclusions

  1. Fragment can be easily reused in activities and layouts
  2. It runs in context of activity, but implements its own Lifecycle and UI
  3. Fragments can also be without fagments known as headless fragments.
  4. Can be added to activity statically or dynamically
  5. If fragment is added in layout file it cannot be removed during runtime
  6. Fragments don’t subclass Context, so we call getActivity() method to get parent activity’s reference.
  7. setRetainState() vs addToBackStack()
  8. add animation using setCustomAnimations() or setTransition() using constants starting with FragmentTransaction.TRANSIT_FRAGMENT_*****.

Example

You can Download the example here.

References:

  1. Vogella Tutorials
  2. Android Fragments

659 total views, 1 views today

Tags: Fragment Lifecycle, Fragments, Fragments Example, Fragments Sample, onAttached, onCreateView