Basic overview of Android's Fragment

Introduction to this section

Well, in the last chapter, we reviewed the four major components of Android: Activity, Service, BroadCastReceiver, ContentProvider and the link between them: Intent, and this chapter brings you a Fragment (fragment) In this section, we will introduce some basic concepts and usage of this Fragment! Official documentation: Fragment


1. Basic concepts

1) What the hell is it and what is it for?

Answer: Fragment is a new API introduced after Android 3.0. Its original intention is to adapt to large-screen tablet computers. Of course, it is still the darling of tablet APP UI design, and we will also add this Fragment to ordinary mobile phone development. , We can regard it as a small Activity, also known as an Activity fragment! Think about it, if we have a large interface, we only have one layout, how troublesome it will be to write the interface, and if there are many components, it will be very troublesome to manage! And using Fragment, we can divide the screen into several pieces, and then group them for a modular management! In this way, it is more convenient to dynamically update the user interface of the Activity during the running process! In addition, Fragment cannot be used alone. It needs to be nested in Activity. Although it has its own life cycle, it will still be affected by the life cycle of the host Activity. For example, if the Activity is destroyed by destory, it will also be destroyed!

The following figure is a Fragment given in the document corresponding to different situations between mobile phones and tablets:

PS: A simple news browsing page, using two Fragments to display the news list and news content respectively;


2) Life cycle diagram of Fragment


3) Core points:

Here are some key points of using Fragment:

  • Introduced after version 3.0, that is, minSdk must be greater than 11
  • Fragment needs to be nested in Activity, and of course it can be nested in another Fragment, but this nested Fragment also needs to be nested in Activity. Indirectly speaking, Fragment still needs to be nested in Activity!! Affected by the life cycle of the host Activity, of course it also has its own life cycle! In addition, it is not recommended to nest Fragment inside Fragment because the life cycle of Fragment nested inside is uncontrollable!!!
  • The official document says that at least three methods need to be implemented when creating a Fragment: onCreate( ), onCreateView( ), OnPause( ); but it seems that it is possible to write only one onCreateView...
  • The life cycle of Fragment is similar to that of Activity: three states:
    Resumed: The Fragment in the permission is visible
    Paused: The Activity is visible, but cannot get the focus
    Stopped: ①Call addToBackStack(), the Fragment is added to the Bcak stack ②The Activity turns to Background, or the Fragment is replaced/deleted
    ps: The fragment in the stopped state is still alive (all state and member information are maintained by the system), however, it is no longer visible to the user, and if the activity is killed, it will also be killed.

4) Several subclasses of Fragment:

ps: Many times we directly rewrite Fragment, inflate loads the layout to complete the corresponding business, subclasses are not used much, and we will study in depth when needed!

  • Dialog: DialogFragment
  • List: ListFragment
  • Option settings: PreferenceFragment
  • WebView interface: WebViewFragment

5) Whether to use the Fragment under the App package or the v4 package:

Problem overview:

I believe that many friends will encounter the following situation when using Fragment:

So do we use the Fragment under android.app or the Fragment under the android.support.v4.app package?

Answer: Actually, it’s all right. As I said earlier, Fragment was introduced after Android 3.0 (API 11), so what if the developed app needs to run on a version below 3.0? For example, 2.3, which still has a little market share! So, the v4 package This is how it came into being, and it can be compatible to version 1.6 at least! As for which package to use, it depends on your needs. Now the market share of mobile phones under 3.0 is actually not much. The street is all above 4.0, and 6.0 will be released in October. What do you think... So at this time, you can directly Use the Fragment under the app package and then call the relevant methods, usually there is no problem; if your Fragment uses the app package, both FragmentManager and FragmentTransaction need to be in the app package! Either use all apps, or all use v4, otherwise it will report an error! Of course, if you want your own app to be compatible with low-version mobile phones, then you can choose to use the v4 package!

Points to note when using Fragment under the v4 package:

  • ①If you use the Fragment under the v4 package, then the Activity you are in must inherit FragmentActivity! Case: Today, I loaded the fragment statically in the xml file, and then rewritten the Fragment, but an error was reported when loading the Activity , The general hint is that the Fragment is wrong or nothing can be found. The name attribute has been changed several times and it is still wrong! Finally, I found out that it is because of the v4 package. Just change your Activity to FragmentActivity!
  • ② I wrote the following code before, and then reported an error: 

     It’s a bit baffling. Fragment, FragmentManager, and FragmentTransaction all use the v4 package. Activity also inherits FragmentActivity? It’s ok to change it to an app package, but doesn’t this conflict with our premise of using the v4 package? In fact, there are The solution?
    Answer: Just change getFragmentManager ( ) to getSupportFragmentManager ( )

2. Create a Fragment

1) Statically load Fragment

Implementation process:

Sample code:

Step 1: Define the layout of the Fragment, which is the display content of the Fragment.
Step 2: Customize a Fragment class, you need to inherit Fragment or its subclasses, rewrite the onCreateView() method and call in this method: inflater.inflate() method loading The layout file of Fragment, and then return the loaded view object

public class Fragmentone extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment1, container,false);
        return view;
    }   
}

Step 3: Add the fragment tag to the layout file corresponding to the Activity that needs to load the Fragment. Remember, the name attribute is a fully qualified class name, which is to include the package name of the Fragment, such as:

<fragment
    android:id="@+id/fragment1"
    android:name="com.jay.example.fragmentdemo.Fragmentone"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

Step 4:  Activity calls setContentView() in the onCreate() method to load the layout file!


2) Dynamically load Fragment

Implementation process:

Sample code:  Here is a demonstration of switching Fragments when the horizontal and vertical screens are switched:

The Fragment and layout code will not be posted, and the key code of MainActivity will be pasted directly:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Display dis = getWindowManager().getDefaultDisplay();
        if(dis.getWidth() > dis.getHeight())
        {
            Fragment1 f1 = new Fragment1();
            getFragmentManager().beginTransaction().replace(R.id.LinearLayout1, f1).commit();
        }
        
        else
        {
            Fragment2 f2 = new Fragment2();
            getFragmentManager().beginTransaction().replace(R.id.LinearLayout1, f2).commit();
        }
    }   
}

3. Fragment management and Fragment affairs


4. Interaction between Fragment and Activity

Maybe some friends don’t like to look at pictures, so let’s introduce them in words:

1) Component acquisition

Fragment gets components in Activity:  getActivity().findViewById(R.id.list);
Activity gets components in Fragment (according to id and tag): getFragmentManager.findFragmentByid(R.id.fragment1);


2) Data transfer

①Activit transfers data to Fragment:

Create a Bundle packet in the Activity, call setArguments(bundle) of the Fragment instance to pass the Bundle packet to the Fragment, then call getArguments in the Fragment to obtain the Bundle object, and then parse it.

②Fragment transfers data to Activity

Define an internal callback interface in the Fragment, and then let the Activity containing the Fragment implement the callback interface, and the Fragment can pass data through the callback interface. Callback, I believe many people know what it is, but they can’t write it out. Online Baidu's "fragment transfers data to Activity" is all the code of Mr. Li Gang. I'm really speechless. Let's write some code here. I believe readers can understand it at a glance:

Step 1: Define a callback interface: (in Fragment)

/*Interface*/   
public interface CallBack{   
    /*Define a method to get information*/   
    public void getResult(String result);   
}  

Step 2: Interface callback (in Fragment)

/*Interface callback*/   
public void getData(CallBack callBack){   
    /*Get the information of the text box, of course you can also pass other types of parameters, depending on your needs */   
    String msg = editText.getText().toString();   
    callBack. getResult(msg);   
}  

Step 3: Use the interface callback method to read data (in Activity)

/* Use interface callback method to get data*/   
leftFragment.getData(new CallBack() {   
 @Override   
       public void getResult(String result) { /*Print information*/   
            Toast.makeText(MainActivity.this, "-->>" + result, 1).show();   
            } 
        });

Summarize the method:  -> Define an interface in Fragment, define an abstract method in the interface, and set the type of data parameter you want to pass; ->
Then write an abstract method in the interface to call the data to be passed Pass it
-> Then it is Activity, call the method provided by Fragment, and then read the data when rewriting the abstract method!!!

③Data transfer between Fragment and Fragment

In fact, this is very simple. Find the fragment object that needs to accept data, and directly call setArguments to pass the data in. Usually, when replacing, that is, when the fragment jumps, the data is passed, so you only need to call after initializing the Fragment to jump Its setArguments method can pass in data!
If two Fragments need to transfer data immediately instead of jumping, you need to obtain the data passed by f1 in Activity first, and then pass it to f2, which is to use Activity as the medium~

The sample code is as follows:

FragmentManager fManager = getSupportFragmentManager( );
FragmentTransaction fTransaction = fManager.beginTransaction();
Fragmentthree t1 = new Fragmentthree();
Fragmenttwo t2 = new Fragmenttwo();
Bundle bundle = new Bundle();
bundle.putString("key",id);
t2.setArguments(bundle); 
fTransaction.add(R.id.fragmentRoot, t2, "~~~");  
fTransaction.addToBackStack(t1);  
fTransaction.commit(); 

5. Take a life cycle diagram:

After thinking about it, I decided to take you through the life cycle diagram to deepen your understanding of the Fragment life cycle:

①When Activity loads Fragment, call the following methods in turn:  onAttach  ->  onCreate  ->  onCreateView  ->  onActivityCreated  ->  onStart  -> onResume

②When we create a suspended dialog-style Activity, or others, it is to make the Activity where the Fragment is located, but not get the focus  onPause

③When the dialog box is closed, the Activity gains focus again:  onResume

④ When we replace Fragment and call addToBackStack() to add it to the Back stack  onPause -> onStop -> onDestoryView  ! ! Note that the Fragment has not been destroyed at this time!!!

⑤ When we press the back button on the keyboard, Fragment will be displayed again:  onCreateView -> onActivityCreated -> onStart -> onResume

⑥If after we replace, the addToBackStack() method is not called to add the Fragment to the back stack before the transaction commit ; or if the Activity is exited, the Fragment will be completely ended, and the Fragment will enter the destruction state  onPause  ->  onStop  - >  onDestoryView  ->  onDestory  ->  onDetach

Guess you like

Origin blog.csdn.net/leyang0910/article/details/131449474