When talking about development for Android it is impossible not to mention fragments.

What is Fragment?

Fragment is special element interface designed to make it easier to create responsive applications that work on both smartphones and tablets.

A Fragment contains interface elements within itself, just like an Activity, however, there are several key differences between the two concepts:

  • Fragment contained inside Activity.
  • Inside Activity there may be several fragments, that is, there can be several fragments on the screen at once, whereas Activity always alone at any given time.

Implementing an application without fragments

Let's look at a specific example to better understand how this works.

Let's imagine that we have an application containing two screens:

  • Screen with news feed.
  • A screen with details about the news opens by clicking on a list item in the previous Activity.

This is what it looks like on the phone:


It turns out that we have two Activities, each of which contains certain interface elements. Let these be FeedActivity for the first screen and DetailActivity for the second screen.

Now imagine that we also need to make an application for the tablet:


In this case, we display content from both screens on one screen, using the same elements. It turns out that we need a third Activity, for example, TabletFeedActivity.

Will this approach work? Yes. Is it correct? Absolutely not.

When using this approach, not only do we create additional unnecessary Activity, but we are also deprived of the opportunity to reuse the code - almost all the code in TabletFeedActivity will simply be copied from FeedActivity and DetailActivity!

And here fragments come to our aid!

Implementing an Application with Fragments

We leave FeedActivity and DetailActivity , but introduce two additional classes - FeedFragment ( Fragment #1 in the picture below) and DetailFragment ( Fragment #2 in the picture below).

In case of using a phone, FeedFragment is located in FeedActivity and DetailFragment is located in DetailActivity:

If the application is running on a tablet, we add both fragments to FeedActivity, DetailActivity is not used at all. All!


This way we don’t write unnecessary code and our application becomes fully adaptive.

Same as with Activity, y fragment there is a life cycle.

A Fragment can have three states:

  • Stopped- Fragment is not visible on the screen. It exists, but is not available for user interaction and can be destroyed if its associated Activity is destroyed.
  • Suspended- Fragment is visible on the screen, but can be covered by other interface elements (for example, there is another Activity in the foreground).
  • Resumed- Fragment is visible on the screen and accessible to the user.

Look at the table of fragment callbacks, which are called accordingly when the Activity state changes:

Let's look at some of them.

  • onAttach() - Fragment"attached" to Activity.
  • onCreate() - Fragment is being created.
  • onCreateView() - called to create interface elements (for example, an inflate from XML).
  • onActivityCreated() - called after the onCreate() method has been processed in Activity.
  • onDestroyView() - called when the View created in onCreateView is "detached" from the fragment.
  • onDetach() - Fragment"detachs" from Activity.

In general, everything is very similar to Activity, with the exception of some new callbacks.

Let's try this in practice

Adding fragments

Let's create an application that will have two fragments:

  • A fragment with switches that we use to select a color.
  • A fragment simply filled with the selected color.

On the phone there will be two screens - on the first we select a color, after which the Activity is launched with a fragment displaying the color.

The tablet will have only one screen with two-panel interface, just like in the example I gave above.

First, let's figure out how we can create a fragment and add it to an Activity.

Create a new project, and in it - a new fragment:

Public class SelectionFragment extends Fragment ( public SelectionFragment() ( ) @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) ( return super.onCreateView(inflater, container, savedInstanceState); ) )

Note: The fragment must have a constructor without parameters, and there must be no other constructors, since they will not be called when the fragment is recreated.

We will also create a file with the layout for the fragment - fragment_selection.xml:

Now let’s fill in the layout inside the onCreateView() method:

@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) ( View view= inflater.inflate(R.layout.fragment_selection, container, false); view.setBackgroundColor(Color.RED); return view; )

I set the color to red to make it clear where the fragment is located.

There are two ways to add a fragment to an Activity:

  • Via XML. In this case, it will not be possible to delete the fragment at runtime.
  • At runtime.

Adding a fragment to XML

Let's try to add a fragment to activity_main.xml:

Launch the application:

Adding a fragment at runtime

First of all, let’s replace the MainActivity layout markup with this:

FrameLayout in this case will serve as a container for the fragment.

Now at the end of the onCreate() method in MainActivity, add the following code:

SelectionFragment selectionFragment = new SelectionFragment(); FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .add(R.id.container, selectionFragment) .commit();

We create a fragment, get a fragment manager and add the fragment to the container.

FragmentManager is a special class through which interaction with fragments occurs.

Note: There are two implementations of fragments in the Android SDK: regular and from Support libraries v4. Although most examples on the Internet use the implementation from the Support Library, it's actually not necessary to use it these days, as it was designed to work with earlier snippets. Android versions than 3.0.

Since 3.0 you can use the regular implementation.

When you launch the application, you will see that the result remains the same:

Creating a two-panel layout

So, we will need two layouts for MainActivity: one for phones, second for tablets.

Let's create a layout for tablet. This is done in the same way as usual with one difference:


As you can see, I have selected the qualifier Smallest screen width and entered the value 600. Thus, this layout will only be used on those devices whose screen width is at least 600dp. This roughly corresponds to a tablet with a 7-inch screen diagonal.

Standard layout (for phones) will be like this:

Since Android encourages being as declarative as possible when creating interfaces, and since we won't need to remove or replace the SelectionFragment , we'll declare it directly in XML.

The layout is for tablets will be like this:

Here we use SelectionFragment in exactly the same way, however, it does not occupy the entire screen, but only a third and, in addition, we added a container for the second fragment - we will replace it from runtime, so adding it to XML will not work.

Since we are no longer adding the SelectionFragment dynamically, remove all related code from onCreate() in MainActivity .

Also create a new emulator for the tablet, for example, like this:


Launch the application on it:


As you can see, on a tablet SelectionFragment takes up the left 30% of the screen. The rest of the space is reserved for the second fragment, which is not yet available.

Let's continue by adding radio buttons to select colors.

RadioButton and RadioGroup

RadioButton - a component for creating radio buttons. Since RadioButton should not be used alone, there is also a layout for it - RadioGroup.

RadioGroup is inherited from LinearLayout and contains several RadioButtons. It controls the exclusivity of selection (after all, only one radio button can be selected per unit of time). Thanks to inheritance from LinearLayout, it can be either vertical or horizontal.


Continuation is available on paid plans

And along with it - checking homework by our mentors.

It's very inexpensive - just from 0 ₽ per month!

Figure 2. Life cycle fragment (during the operation)

To create a fragment, you must subclass the class (or an existing subclass of it). The class has code much like the . It contains callback methods similar to operation methods, such as , and . In practice, if you need to convert an existing Android app so that it uses fragments, you simply move the code from the operation callback methods to the corresponding fragment callback methods.

Typically, you need to implement the following lifecycle methods:

The system calls this method when it creates a fragment. In his implementation, the designer must initialize the key components of the fragment that need to be preserved when the fragment is paused or resumed after being stopped. The system calls this method the first time the fragment UI is shown on the display. To render the fragment's UI, this method should return the object that is the root of the fragment's layout. If the fragment does not have a user interface, you can return null. The system calls this method as the first indication that the user is leaving the fragment (this does not always mean that the fragment is being destroyed). It is usually at this point that it is necessary to commit all changes that should be saved outside the scope of the current session user experience (since the user may not go back).

There are also a number of subclasses that may need to be extended instead of using the base class:

Display a movable dialog box. Using this class to create a dialog box is a good alternative to the dialog box helper methods in the . This is because it provides the ability to insert a fragment dialog into an operation-driven back stack for fragments, allowing the user to return to a closed fragment. Displaying a list of adapter-managed elements (such as ) is similar to the . This class provides several methods for managing the list of views, such as a callback method for handling clicks. Displaying a hierarchy of objects in the form of a list, similar to the . This class is useful when creating a Settings operation in an application.

Adding a User Interface

A fragment is typically used as part of an activity's user interface and adds its own layout to the activity.

To create a layout for a fragment, the developer must implement a callback method that Android system Called when it is time for the fragment to render its layout. The implementation of this method must return a object that is the root of the fragment's layout.

Note. If the fragment is a subclass of the class, the default implementation returns the class from the method, so there is no need to implement it.

To return a layout from a method, you can inflate it from a method defined in the XML file. For this purpose, the method provides a .

For example, the code for a subclass of the class that loads the layout from example_fragment.xml might look like this:

Public static class ExampleFragment extends Fragment ( @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) ( // Inflate the layout for this fragment return inflater.inflate(R.layout.example_fragment, container, false); ) )

Creating a Layout

In the code below, the R.layout.example_fragment construct is a reference to a layout resource named example_fragment.xml stored in application resources. For details on creating a layout in XML, see this article.

For an example of an operation that uses a fragment as a background thread, without a user interface, see the FragmentRetainInstance.java code sample included in the SDK samples (and accessible through the Android SDK Manager). The path to it in the system is /APIDemos/app/src/main/java/com/example/android/apis/app/FragmentRetainInstance.java .

Fragment Management

To manage fragments in an operation, you need a class. To get it, you must call the method from the opcode.

Below are the actions that you can perform:

  • get the fragments present in an activity using a method (for fragments that provide a user interface in the activity layout) or (for both fragments that have a user interface and for fragments without one);
  • remove fragments from the stack of transitions using the backward method (simulating pressing a button Back user);
  • register the change listener process in the back stack using the .

additional information These and other methods are described in the class documentation.

As shown in the previous section, you can use the Open class, which allows you to perform transactions on fragments, such as adding and deleting.

Performing transactions with fragments

The great benefit of using fragments in an operation is the ability to add, remove, replace, and do other things with them in response to user input. Any set of changes made to an operation is called a transaction. This can be done using the APIs in . Each transaction can be stored in a back stack that is managed by the operation. This will allow the user to move backward through changes in fragments (similar to moving backward through activities).

Interaction with the operation

public static class FragmentA extends ListFragment ( OnArticleSelectedListener mListener; ... @Override public void onAttach(Activity activity) ( super.onAttach(activity); try ( mListener = (OnArticleSelectedListener) activity; ) catch (ClassCastException e) ( throw new ClassCastException( activity.toString() + " must implement OnArticleSelectedListener"); ) ) ... )

If the operation did not implement the interface, the fragment throws an exception. If successful, the mListener element will contain a reference to the operation's implementation of the OnArticleSelectedListener interface so that Fragment A can share events with the operation by calling methods defined by the OnArticleSelectedListener interface. For example, if fragment A is an extension of the class , then whenever the user clicks on a list item, the system calls in the fragment. This method in turn calls the onArticleSelected() method to use the event in conjunction with the operation:

Public static class FragmentA extends ListFragment ( OnArticleSelectedListener mListener; ... @Override public void onListItemClick(ListView l, View v, int position, long id) ( // Append the clicked item"s row ID with the content provider Uri Uri noteUri = ContentUris.(ArticleColumns.CONTENT_URI, id); // Send the event and Uri to the host activity mListener.onArticleSelected(noteUri); ) ... )

The id parameter passed to the method is the ID of the row containing the selected list item that the operation (or other fragment) uses to retrieve the article from the application object.

For more information about working with a content provider, see the document.

Adding items to the action bar

Fragments can add menu items to activities (and therefore to ) by implementing . However, for this method to accept calls, it must be called at runtime to indicate that the fragment intends to add items to the Options Menu (otherwise the fragment will not accept the method call).

Any items added by the fragment to the Options Menu are added to the existing ones. Additionally, the fragment receives method callbacks when the user selects a menu item.

The developer can also register a view in their fragment's layout to provide context menu. To do this, call the method. When the user opens the context menu, the fragment accepts a method call. When the user selects a menu item, the fragment receives a method call.

Note. Although the fragment receives a callback on the "menu item selected" event for each item it adds, the activity first receives the corresponding callback when the user selects a menu item. If the activity's existing callback implementation for the menu item selected event does not handle the selected item, the event is passed to the callback method in the fragment. This is true for Option Menus and context menus.

For detailed menu information, see the developer's guides and

Fragment lifecycle management

Figure 3. Impact of the activity lifecycle on the fragment lifecycle

Managing the lifecycle of a fragment is in many ways similar to managing the lifecycle of an operation. Like an operation, a fragment can exist in one of three states:

Resumed The fragment is visible during the operation. Suspended Another activity is running and has focus in the foreground, but the activity containing the fragment is still visible (the foreground activity is partially transparent or does not fill the entire screen). Stopped The fragment is not visible. Either the container operation has stopped, or the fragment has been removed from it but added to the back stack. The stopped fragment is still active (all information about the state and elements is saved in the system). However, it is no longer visible to the user and will be destroyed if the operation is destroyed.

Here again, the analogy with an operation is visible: the developer can save the state of the fragment with help in case the operation process is destroyed, and the developer needs to restore the state of the fragment when the operation is recreated. State can be saved during execution of a callback method in a fragment and restored during execution of , or . For more information about persistence, see the document.

The most significant lifecycle difference between an operation and a fragment is how they are stored in their respective backstacks. By default, an operation is placed on the system-managed back stack for operations when it stops (so that the user can return to it using the button Back, as described in the article). At the same time, the fragment is placed on the operation-driven back stack only when the developer explicitly requests that a particular instance be saved by calling a method during the transaction that deletes the fragment.

Otherwise, managing the lifecycle of a fragment is very similar to managing the lifecycle of an operation. That's why practical recommendations are also applicable to fragments. At the same time, the developer needs to understand how the life cycle of an operation affects the life cycle of a fragment.

Attention! If you need an object inside a class object, you can call the . However, the developer must be careful to only call the method when the fragment is attached to an activity. If the fragment is not yet attached or was undocked at the end of its lifecycle, the method will return null.

Alignment with the activity life cycle

The lifecycle of the activity containing the fragment directly affects the lifecycle of the fragment, so that each activity lifecycle callback results in a similar callback for each fragment. For example, when an operation accepts a call, each of its fragments accepts .

However, fragments have several additional lifecycle callback methods that provide unique interaction with an operation to perform actions such as creating and destroying the fragment UI. These are the methods:

OnCreate() , the fragment inside this operation just takes a callback method.

When an operation enters the "resumed" state, you can freely add and remove fragments to it. Thus, the fragment's lifecycle can be independently modified only while the operation remains in the "resumed" state.

However, when the operation exits this state, the fragment's progress through its lifecycle is again carried out by the operation.

Example:

To summarize everything covered in this document, let's look at an example operation that uses two fragments to create a two-panel layout. The operation below includes one fragment to display a list of Shakespeare plays and another to display a summary of the play selected from the list. The example shows how different fragment configurations should be organized depending on the screen configuration.

Note. The complete source code for this operation is in the section.

Main operation applies layout in the usual way, in the method:

@Override protected void onCreate(Bundle savedInstanceState) ( super.onCreate(savedInstanceState); setContentView(R.layout.fragment_layout); )

The fragment_layout.xml layout is used here:

Using this layout, the system creates an instance of the TitlesFragment class (list of plays) as soon as the operation loads the layout. In this case, the object (which will contain a fragment with a summary) takes up space on the right side of the screen, but initially remains empty. As will be shown below, the fragment is not placed in until the user selects an item in the list.

However, not all screens are wide enough to display a summary next to the playlist. Therefore, the layout described above is used only in landscape screen orientation and is stored in the file res/layout-land/fragment_layout.xml.

When the device is in portrait orientation, the system applies the layout below, which is stored in the file res/layout/fragment_layout.xml:

In this layout, only the TitlesFragment object is present. This means that when the device is in portrait orientation, only the list of plays is visible. When the user clicks on a list item in this configuration, the application starts a new activity to display the summary rather than loading a second fragment.

Next you can see how this is implemented in the fragment classes. First comes the code for the TitlesFragment class, which displays a list of Shakespeare's plays. This snippet extends the class and uses its functions to do the basic work with the list.

As you examine the code, notice that there are two possible behaviors in response to a user clicking a list item. Depending on which of the two layouts is active, either a single activity creates and displays a new summary fragment (by adding the fragment to an object), or a new activity (displaying the fragment) is launched.

The second fragment, DetailsFragment, displays a summary of the play selected in the TitlesFragment list:

Let's remember the code of the TitlesFragment class: if the user clicks on a list item, and the current layout Not includes the R.id.details view (which owns the DetailsFragment), then the application runs a DetailsActivity to display the element's contents.

Public static class DetailsActivity extends Activity ( @Override protected void onCreate(Bundle savedInstanceState) ( super.onCreate(savedInstanceState); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) ( // If the screen is now in landscape mode, we can show the // dialog in-line with the list so we don"t need this activity. finish(); return; ) if (savedInstanceState == null) ( // During initial setup, plug in the details fragment.DetailsFragment details = new DetailsFragment(); details.setArguments(getIntent().getExtras()); getFragmentManager().beginTransaction().add(android.R.id.content, details).commit(); ) ) )

Note that in the landscape configuration, this activity completes itself so that the main activity can take control and display the DetailsFragment next to the TitlesFragment . This can happen if the user starts a DetailsActivity in portrait screen orientation and then flips the device to landscape orientation (resulting in the current activity being restarted).

Additional code samples using snippets (and full files) source code this example) are available in the Demos API sample application (which can be downloaded from ).

For general understanding, I also decided to study the life cycle of a fragment in conjunction with the life cycle of an activity, which occurs when an activity with a fragment is launched and destroyed. The result is the following:


List of intercepted fragment methods

Three main methods that are used in almost any application:

onCreate— initialization of the internal components of the fragment with the saved data.

onCreateView— generation of a component for display.

onPause— handling the situation when a fragment loses focus.

Description of all methods in the order they are called:

onAttach— the first connection of a fragment to an activity. The activity to which the connection is made is transmitted here.

onCreate— fragment initialization. Data from the Bundle class about the last state of the fragment in its previous life, if there was one, saved earlier, for example, in the onSaveInstanceState method, is passed here to restore this state. At this point, the activity is still in the process of creation.

onCreateView — formation of the view for display. Returns the view of the fragment. Can return null for non-visual components. Data from the Bundle class about the last state of the fragment is passed here, as well as the activity container where the fragment and the markup “inflator” will be connected.

onViewCreated - Called when the view is formed. The generated view and Bundle class data about the last state of the fragment are passed here. Used to finalize the view before restoring the saved state. At this point the view is not yet attached to the fragment.

onActivityCreated - final initialization. Called when the activity's onCreate() method has returned. The activity is created, the fragment is inserted into it. Used, for example, to restore the state of a fragment. Data from the Bundle class about the last state of the fragment is passed here.

onViewStateRestored — initialization of the view based on the saved state. Called when the view's saved state is restored.

onSaveInstanceState— saving the state of the fragment. It only works if the fragment stops and can be killed by the system, but is actually still needed. This happens, for example, when the next activity is called, when the home button is pressed, and also in the case of a complete destruction of the activity and its creation anew as a result of a change in the device configuration (change of language, input device, screen orientation, etc.). An object of the Bundle class that stores the state of the activity is passed to the onCreate, onPostCreate and onRestoreInstanceState methods. Attention! The method can be called at any time before onDestroy!

onDestroyView— Called when a view is detached from a fragment. The next time the fragment is displayed, a new view will be generated.

onDetach- Called before detaching the fragment from the activity.

Last updated: 10/30/2015

Each fragment class inherits from the base Fragment class and has its own life cycle, consisting of a number of stages:

    onAttach() : When this method is executed, the fragment is associated with a specific activity. At this point, the fragment and activity are not yet fully initialized.

    onCreate() : the fragment is created. This method is called after calling the corresponding onCreate() method of the activity.

    onCreateView() : the fragment creates the visual interface

    onActivityCreated() : Called after the activity is created. From now on, interface components can be accessed through the findViewById() method

    onStart() : Called when the fragment becomes visible

    onResume() : the fragment becomes active

    onPause() : the fragment remains visible, but is no longer active

    onStop() : the fragment is no longer visible

    onDestroyView() : The interface representing the fragment is destroyed

    onDestroy() : permanent destruction of the fragment

In the fragment class code, we can override all or some of these methods.

Since fragments are often used for certain purposes, for example, to display a list of some objects, by default we have access to classes derived from Fragment, which already have certain capabilities:

    ListFragment: manages a list of elements using one of the adapters

    DialogFragment: used to create dialog boxes

    PreferenceFragment: used to manage application preferences

You can use regular classes to create a new fragment. However, the environment Android Studio already offers a number of built-in templates:

When creating, you will be asked to set the project name, the name of the interface markup file, and a number of other options:

The fragment class generated by Android Studio will be largely similar to those previously used:

Package com.example.eugene.testapp; import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class BlankFragment extends Fragment ( private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; // Factory for creating the fragment public static BlankFragment newInstance(String param1, String param2) ( BlankFragment fragment = new BlankFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; ) public BlankFragment() ( // Constructor ) @Override public void onCreate(Bundle savedInstanceState) ( super.onCreate(savedInstanceState); if (getArguments() != null) ( mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); ) ) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) ( return inflater.inflate(R.layout.fragment_blank, container, false); ) public void onButtonPressed(Uri uri) ( if (mListener != null) ( mListener.onFragmentInteraction(uri); ) ) @Override public void onAttach(Activity activity) ( super.onAttach(activity); try ( mListener = (OnFragmentInteractionListener) activity; ) catch (ClassCastException e) ( throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); ) ) @Override public void onDetach() ( super.onDetach(); mListener = null; ) public interface OnFragmentInteractionListener ( public void onFragmentInteraction(Uri uri); ) )

Therefore, we can create fragments manually, or use one of the templates provided by Android Studio.

Creating a good UI is difficult, especially if you don't have much experience in this field yet. So here's to you quick test to know the question: if you are used to the fact that a new window necessarily needs an Activity, or instead of smooth animation in a freshly written program for some reason convulsions occur, this article is for you :)

Rake Activity

Most tutorials demonstrating the tricks of Android development start the same way: inexperienced developers are asked to write everything visual elements directly into the XML markup of the main Activity. It looks something like this:

Public class MainActivity extends AppCompatActivity ( @Override protected void onCreate(Bundle savedInstanceState) ( super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ...

This kind of design becomes a habit, and the project is filled with new Activities with increasingly complex markup. As a result - even minimally useful application becomes overgrown with an Activity stack, gobbling up all RAM, and stones and deuces are flying at the developer on Google Play.

And all because the Android OS does not promise to keep your Activities alive. As you remember, these components exist independently of each other, having a special life cycle. If the Activity goes into the onPause state, and this happens quite often, it becomes Schrödinger's cat: you cannot know in advance whether it will be alive or not.

By using additional Activities to display menus and other little things, you endanger all logical connections within the application. Activities are collected on a stack, and the OS can start unloading them one by one or in a group. When the user wants to return to the previous window, the Activity may already be destroyed, and the user will drop out of the application.

In addition to problems with preserving logic, there is also the routine of supporting OOP code: interfaces tightly tied to Activity are almost impossible to develop further. Scaling, quick replacement some elements to others, animation - all this will be very difficult to implement in new versions of the application.

Thanks to the fashion for a single ecosystem, everything mobile applications were generally very similar. You just have to find the path and practice a little, and then the quality begins to grow quickly. Following the "criticize - suggest" principle, we will now write an application that implements a universal user interface. This will be interesting not only from an academic point of view - I’m sure you can easily integrate the code written today into your projects. So, let's begin!

Fragments

To make working with the UI easier and faster, Google created a Fragment - a class - a layer between the Activity and the visual components of the program. On the one hand, it is a container for any View objects that can be shown to the user. On the other hand, there is a continuation of the Activity, from which Fragment receives all information about changes in the life cycle.

Fragments, like Activity, have their own (albeit more original) life cycle. For example, it is impossible to work with the UI immediately after creating a fragment; you need to wait for all elements to load - after the onCreate method, the onCreateView method will be executed, where the elements can be loaded.

Public class FragmentOne extends Fragment ( ... public View onCreateView(...) ( View view =inflater.inflate(R.layout.fragment_one, container,false); TextView textView = (TextView)view.findViewById(R.id. fo_text); textView.setText("Hello, i"m first fragment!"); return view; ...

In a fragment, you can also override any methods that monitor the state of the window. So, if the application goes into the background, onPause will be executed in the Activity, and then the method with exactly the same name will be executed here. This can be useful - convenient for disconnecting from third-party objects, such as bound services.

FragmentTransaction

Knowing that working with fragments would be intense, Google created special tools for this in advance. The FragmentManager and FragmentTransaction classes accumulate all processes: creating new fragments and deleting them, transferring data, and so on.

There is no need to create a FragmentManager object, it is already in every Activity, you just need to get a link to it. And all actions will go through FragmentTransaction , which will then independently transfer data to the fragment manager.

FragmentManager manager = getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction();

I would like to note that classes that work with fragments are available in two versions. I recommend using more new version- these are those that have the line android.support.v4 in the import path. This is a large library created for organizing backward compatibility. Google Company treats devices with care on all OS versions, and libraries allow you to use development innovations even when working with the old API.

Import android.support.v4.app.FragmentTransaction; import android.support.v4.app.Fragment;...

FrameLayout

Often data in the UI comes dynamically, depending on ongoing events. To have somewhere to place a picture or text, there is a special container - FrameLayout. This is its main task - to reserve space on the screen for any object of the View class, which can be loaded later. Fragments also live in such containers.

You can add a new fragment to FrameLayout in different ways: FragmentTransaction has similar functionality for replacing and adding methods.

Transaction.replace(R.id.frame_container, fragmentObject);

Despite the external similarity, you need to have a good understanding of what results you can achieve. The replace method works very simply - it will add a fragment and, if there was something in the container before, it will delete the old fragments.

Transaction.add(R.id.frame_container, fragment);

The add method creates a stack of fragments, and each new call pushes a new instance to the top of the stack. It is important that when a new fragment appears, old objects on the stack do not receive any notifications and act as if nothing had happened. This means that the onPause method for them will not be executed and they will continue to consume device resources, although the user will no longer see them.

Such waste of allocated memory can be justified, for example, if you want to organize data preprocessing: a fragment can load something while it is invisible, and then show the finished result.

There can be several actions with fragments; they will accumulate until the commit method is executed.

Transaction.commit();

Continuation is available only to members

Option 1. Join the “site” community to read all materials on the site

Membership in the community within the specified period will give you access to ALL Hacker materials, increase your personal cumulative discount and allow you to accumulate a professional Xakep Score rating!