Some Fragment main features
A Fragment represents a particular operation or interface running within a larger activity.
- Fragments enable more modulars Activity design, making it easier to adapt an application to different screen orientations and multiple screen sizes.
- Fragments must be embedded in Activities; they cannot run independent of activities.
- Most Fragments define their own layout of views that live within the Activity’s view hierarchy. However, a Fragment can implement a behavior that has no user interface component.
- A Fragment has its own lifecycle, closely related to the lifecycle of its host Activity.
- A Fragment can be a static part of an Activity, instantiated automatically during the Activity’s creation.
- Or, you can create, add and remove Fragments dynamically in an Activity at run-time.
Fragment Life Cycle
Important methods details:
- onAttach(): Fragment instance is associated with an activity instance.The Fragment and the Activity is not fully initialized.
- onCreate(): The system calls this method when creating the Fragment. You should initialize essential components of the Fragment that you want to retain when the Fragment is paused or stopped, then resumed.
- onCreateView(): called when it's time for the Fragment to draw it's user interface for the first time. To draw a UI for your Fragment, you must return a View component from this method that is the root of your Fragment's layout. You can return null if the fragment does not provide a UI.
- onActivityCreated(): called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context object.
- onStart(): this method is called once the Fragment gets visible.
- onResume(): Fragment becomes active.
- onPause(): the system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.
- onStop(): Fragment going to be stopped by calling this.
- onDestroyView(): Fragment view will destroy after call this method.
- onDestroy(): called to do final clean up of the fragment's state but not guaranteed to be called by the Android platform.
Types of Fragments
- DialogFragment: displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog helper methods in the Activity class, because you can incorporate a Fragment dialog into the back stack of Fragments managed by the Activity, allowing the user to return to a dismissed fragment.
- ListFragment: displays a list of items that are managed by an adapter similar to ListActivity. It provides several methods for managing a ListView, such as the onListItemClick() callback to handle click events.
- PreferenceFragment: displays a hierarchy of Preference objects as a list, similar to PreferenceActivity. This is useful when creating a "settings" Activity for your application.
Sample Project
DEMO VIDEO:
Firstly, create a simple main Activity layout:
Layout design:
Now, turn to Activity programmatically code, we will replace a Fragment to the LinearLayout (as declared with id "container" in the xml file) by FragmentTransaction. Create and commit this process through a FragmentManager and FragmentTransaction instances:
//initial a FragmentTransaction instance fragmentManager = getSupportFragmentManager(); //initial a FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); //add to Transaction fragmentTransaction.add(R.id.container, new SampleFragment(), FRAGMENT_TAG); //replace Fragment to the container layout fragmentTransaction.replace(R.id.container, new SampleFragment(), FRAGMENT_TAG); //invoke this transaction fragmentTransaction.commit();Note: in a Activity, you can replace many Fragments into it, as long as each Fragment has a separate container layout.
And the remove Fragment process is similar like replacing, you can find Fragment instance by the tag name and remove it by this code:
//initial a FragmentManager instance fragmentManager = getSupportFragmentManager(); //initial a FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); //find the Fragment by TAG SampleFragment f = (SampleFragment)fragmentManager.findFragmentByTag(FRAGMENT_TAG); //remove this Fragment fragmentTransaction.remove(f); //invoke command fragmentTransaction.commit();As said above, a Fragment can have it own component view, so in this example, I create a Fragment with this layout: Layout preview:
And the Fragment programmatically code is similar to a normal Activity, overriding some important methods as note above, locate all views and handle Button click event:
package info.devexchanges.fragmentsample; import android.annotation.SuppressLint; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class SampleFragment extends Fragment { private View button; private TextView textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i("Fragment", "Fragment Created!"); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_sample, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); button = view.findViewById(R.id.btn_fragment); textView = (TextView) view.findViewById(R.id.text); button.setOnClickListener(onClickListener()); } private View.OnClickListener onClickListener() { return new View.OnClickListener() { @SuppressLint("SetTextI18n") @Override public void onClick(View view) { textView.setText("Fragment Button Clicked!"); } }; } }Important note:
- To compatible with low API device (lower than 11), you should import android.support.v4.app.Fragment ("support Fragment") instead of android.app.Fragment.
- In the Activity code, if you use support Fragment, please use getSupportFragmentManager() instead of getFragmentManager() to create a FragmentManager instance.
- There is another way to replace Fragment to Activity is use <fragment> tag in the Activity layout file but I'm not recommend, because it's not as flexibility as use FragmentTransaction in java code.
package info.devexchanges.fragmentsample; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { private View btnReplace; private View btnRemove; private FragmentManager fragmentManager; private FragmentTransaction fragmentTransaction; private final static String FRAGMENT_TAG = "fragment"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnRemove = findViewById(R.id.btn_remove); btnReplace = findViewById(R.id.btn_replace); btnReplace.setOnClickListener(onReplaceFragment()); btnRemove.setOnClickListener(onRemoveFragment()); } private View.OnClickListener onRemoveFragment() { return new View.OnClickListener() { @Override public void onClick(View view) { //initial a FragmentManager instance fragmentManager = getSupportFragmentManager(); //initial a FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); //find the Fragment by TAG SampleFragment f = (SampleFragment)fragmentManager.findFragmentByTag(FRAGMENT_TAG); //remove this Fragment fragmentTransaction.remove(f); //invoke command fragmentTransaction.commit(); } }; } private View.OnClickListener onReplaceFragment() { return new View.OnClickListener() { @Override public void onClick(View view) { //initial a FragmentTransaction instance fragmentManager = getSupportFragmentManager(); //initial a FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); //add to Transaction fragmentTransaction.add(R.id.container, new SampleFragment(), FRAGMENT_TAG); //replace Fragment to the container layout fragmentTransaction.replace(R.id.container, new SampleFragment(), FRAGMENT_TAG); //invoke this transaction fragmentTransaction.commit(); } }; } }Output result:
Conclusions
Official docs references:
- Fragment: http://developer.android.com/reference/android/support/v4/app/Fragment.html
- Android support library v4: http://developer.android.com/reference/android/support/v4/app/package-summary.html
- FragmentManager: http://developer.android.com/reference/android/support/v4/app/FragmentManager.html
- FragmentTransaction: http://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html