Lesson 105. Android 3. Fragments. dynamic work

Lesson 105. Android 3. Fragments. dynamic work


In this lesson:

– dynamically working with fragments

We already know how to place static fragments. But, of course, it’s much more interesting to work with them dynamically. The system allows us to add, delete, and replace fragments with each other. In doing so, we can store all these manipulations in BackStack and click the Back button to cancel. In general, everything is comfortable and beautiful.

Let’s create a simple application with two snippets that will be able to:

– add the first snippet
– delete the first snippet
– replace the first fragment with the second fragment
– to switch the save mode in BackStack of fragment operations

Let’s create a project:

Project name: P1051_FragmentDynamic
Build Target: Android 4.1
Application name: FragmentDynamic
Package name: ru.startandroid.develop.p1051fragmentdynamic
Create Activity: MainActivity

IN strings.xml add rows:

Fragment 1
Fragment 2
Add
Remove
Replace
add to Back Stack

We create fragments. As we remember from the last lesson, we will need layout files and classes to inherit android.app.Fragment

fragment1.xml:



	
	

fragment2.xml:



	
	

Fragment1.java:

package ru.startandroid.develop.p1051fragmentdynamic;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment1, null);
  }
}

Fragment2.java:

package ru.startandroid.develop.p1051fragmentdynamic;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2 extends Fragment {

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment2, null);
  }
}

Everything is almost similar to the last lesson, only removed the challenges of a bunch of lifecycle methods with beams.

We draw the main Activity.

main.xml:



	
		
		
		
		
		
	
	
	

Three buttons to add, delete and replace fragments. Checkbox to enable BackStack usage. And FrameLayout is the container that will handle all of the snippets. It must be of type ViewGroup. And the Fragment elements we used in the previous lesson to place snippets are not needed for dynamic work.

MainActivity.java:

package ru.startandroid.develop.p1051fragmentdynamic;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;

public class MainActivity extends Activity {

  Fragment1 frag1;
  Fragment2 frag2;
  FragmentTransaction fTrans;
  CheckBox chbStack;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    frag1 = new Fragment1();
    frag2 = new Fragment2();
    
    chbStack = (CheckBox)findViewById(R.id.chbStack);
  }

  public void onClick(View v) {
    fTrans = getFragmentManager().beginTransaction();
    switch (v.getId()) {
    case R.id.btnAdd:
      fTrans.add(R.id.frgmCont, frag1);
      break;
    case R.id.btnRemove:
      fTrans.remove(frag1);
      break;
    case R.id.btnReplace:
      fTrans.replace(R.id.frgmCont, frag2);
    default:
      break;
    }
    if (chbStack.isChecked()) fTrans.addToBackStack(null);
    fTrans.commit();
  }
}

IN onCreate create a couple of fragments and find a checkbox.

IN onClick we get a fragment manager using the getFragmentManager method. This object is essential for dealing with fragments. Next, we need to use transactions to add / delete / replace the snippet. They are similar to transactions in the database, where we open a transaction, perform database operations, perform commit. Here we open a transaction, perform operations with fragments (add, delete, replace), execute commit.

So, we received a FragmentManager and opened the transaction using the beginTransaction method. Next, determine which button was pressed:

if Add, Then call the add method, in which we pass the container id (the same FrameLayout with main.xml) and the fragment object. As a result, Fragment1 will be placed in the container

if Remove, Then we call the remove method, in which we pass the object of the fragment that we want to remove. As a result, the snippet will be removed from the screen.

if Replace, Then call the replace method, in which we pass the container id and the fragment object. As a result, the current fragment (if any) will be removed from the container and the fragment specified by us will be added.

Next we check the checkbox. If enabled, we add a transaction to BackStack. To do this, we use the addToBackStack method. You can submit a tag line to the input. I pass null.

Well, we call commit, the transaction is complete.

Let’s watch what happened. We save everything, launch the application.

press Add

the first fragment appeared.

press Remove

the fragment is gone.

Once again add the first fragment – click Add. And press Replace

the first fragment was replaced by the second.

press the button back. The application closed because all these snippet operations were not stored in BackStack. Let’s take this opportunity.

We launch the application again and turn on the checkbox add to Back Stack

Perform the same operations: Add, Remove, Add, Replace. We will add the first snippet, delete the first snippet, add the first snippet, replace the second. As a result, we again see the second fragment. Now press the button several times back and we see how operations are performed, the opposite of what we did. When the transactions stored in the stack are completed, the Back button will close the application.

That is, everything is quite simple and understandable. Let me say a few more interesting points.

In this example, I performed only one operation in each transaction. But, of course, there may be more.

When we delete a snippet and do not add a transaction to BackStack, the snippet is destroyed. If the transaction is added to BackStack, then when deleted, the fragment is not destroyed (onDestroy is not called), and stops (onStop).

As a standalone work, try modifying the app a bit and adding two pieces at a time to one container. The result may surprise you)

In the next lesson:

– Consider the interaction between Activity and its fragments




Discuss in the forum [68 replies]

Leave a Comment