Fragments – every day tips

#Tip 1 – static newInstancemethod pattern

Note: Avoid setter methods and parametrized constructors to modify fragment state, because platform uses only default (0 parameter) constructor, arguments bunde and saved state bundle to restore it later.

 

#Tip 2 – single fragment in Activity

If your activity role is only to show fragment don’t create custom layout with container to add your fragment. Use default activity root container identified by android.R.id.content.

 

#Tip 3 – nested/child fragments will not get onActivityResult callback

Activities started with startActivityForResult will automatically call onActivityResult on ‘first level’ (added directly to Activity FragmentManager) Fragments.
If you want to use activity result mechanism with child fragments, you have to pass this callback on your own.

 

#Tip 4 – Use setRetainInstance(true) only in non-UI fragments

setRetainInstance(true) method will ensure that your fragment will survive orientation changes and its activity recreation. Using this flag in Fragments with UI/widget/view references could potentially cause memory leaks, like this:

After orientation change and before second onCreateView TextView reference will hold old view with all it’s context – which is an old Activity. This means two Activities in memory at the same time, one new and one old held because of this TextView reference until mMyTextView = (TextView) root.findViewById(R.id.my_text); will not be called again

 

#Tip 5 – setRetainInstance(true) cannot be used with nested/child fragments

If you try to use this flag in your child fragment you will get exception java.lang.IllegalStateException: Can't retain fragements that are nested in other fragments

 

#Tip 6 – Custom attributes on XML initialized fragments

If you want to create fragment via XML layout, you could declare custom style attributes and read them later in onInflate (Context context, AttributeSet attrs, Bundle savedInstanceState)

 

#Tip 7 – Debug your fragment

If you want to check what is the current state of FragmentManager and it’s fragments just use FragmentManager.dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) method like this:

 

#Tip 8 – Prefer android.support.v4.app.Fragment over android.app.Fragment

Fragments packed into v4 support library are created on newer code. Support library could receive faster updates and bugfixes in contrast to android.app.Fragment which is a part of Android framework released with different version on different devices (with a small probability of receiving updates).

 

Michał Łuszczuk

Lead Android developer @Blix-Qpony Group