Android Fragment implements fragment switching

Table of contents

Fragment theory:

Fragment life cycle

Concrete example: switching fragments

Create an Android application SwitchFragment

create shards

Open the main interface:

Fragment interface class realizes the function

optimization:


Fragment theory:

Fragment is a new API introduced by Android 3.0. It represents a sub-template of Activity, so fragment can be understood as an Activity fragment. Fragment must be "embedded" in Avtivity, so Fragment also has its own life cycle, but the life cycle of Fragment is controlled by Activity, that is to say, when Activity stops, all Fragments in Activity will be stopped, and other states are the same .

Fragment life cycle

Attach and detach: onAttach() + onDetach()
Create and destroy: onCreate() + onDestroy()
Create and destroy views: onCreateView() + onDestroyView()
Visible and invisible: onStart() + onStop()
can be interactive and Non-interactive: onResume() + onPause()
Original link: https://blog.csdn.net/howard2005/article/details/127853054

Concrete example: switching fragments

Create an Android applicationSwitchFragment

 Created successfully:

Insert image material

Copy the three background images to drawablethe directory

 In character resource string resource filesstrings.xml里面输入代码:

 Specific code:

<resources> 
    <string name="app_name">Switch Fragment</string> 
    <string name="first_fragment">First Fragment</string> 
    <string name="second_fragment">Second Fragment</string> 
    < string name="third_fragment">The third fragment</string> 
    <string name="next_fragment">Next fragment</string> 
</resources>

Open the main layout resource fileactivity_main.xml输入 代码:

Specific code:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

</FrameLayout>

create shards

(1) Create the first shard

 Set Fragment Name - FirstFragment

 Created successfully:

 Modify the layout resource file of the first fragment fragment_first.xml

 Specific code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/img1"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".FirstFragment">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:text="@string/first_fragment"
        android:textSize="50sp"
        android:textColor="#ff0000"/>
    <Button
        android:id="@+id/btn_next_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="doNextFragment"
        android:text="@string/next_fragment"
        android:textSize="30sp"/>


</LinearLayout>

Create the second shardSecondFragment

 Created successfully:

  Modify the layout resource file fragment_second.xml of the second fragment

Specific code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/img2"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".SecondFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:text="@string/second_fragment"
        android:textSize="50sp"
        android:textColor="#00ff00"/>
    <Button
        android:id="@+id/btn_next_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="doNextFragment"
        android:text="@string/second_fragment"
        android:textSize="30sp"/>
</LinearLayout>

Create a third shardThirdFragment

 Created successfully:

 Modify the layout resource file of the third fragment  fragment_third.xml

 Specific code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/img3"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".ThirdFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:text="@string/third_fragment"
        android:textSize="50sp"
        android:textColor="#0000ff"/>
    <Button
        android:id="@+id/btn_next_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="doNextFragment"
        android:text="@string/third_fragment"
        android:textSize="30sp"/>
</LinearLayout>

Open the main interface:

 

 Specific code:

package net.zyt.switch_fragment; 

import androidx.appcompat.app.AppCompatActivity; 
import androidx.fragment.app.Fragment; 
import androidx.fragment.app.FragmentManager; 

import android.os.Bundle; 

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        //Use the layout resource file to set the user interface 
        setContentView(R.layout.activity_main); 


        //Get the fragment manager 
        FragmentManager fm=getSupportFragmentManager(); 

        //In the main container Add the first fragment inside 
        fm.beginTransaction().add(R.id.container,new FirstFragment()).commit(); 

    } 
}

Fragment interface class realizes the function

(1) The first fragment interface class realizes the function,打开FirstFragment

 

 Specific code:

package net.zyt.switch_fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FirstFragment extends Fragment {


    private Button btnNextFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //获取碎片视图
        View view=inflater.inflate(R.layout.fragment_first,container,false); 
        //Get the control instance through the resource identifier 
        btnNextFragment=view.findViewById(R.id.btn_next_fragment); 
        //Register the click event listener for the button 
        btnNextFragment.setOnClickListener(new View.OnClickListener() { 
            @Override 
            public void onClick(View v) { 
                //Switch to the second fragment 
                getFragmentManager(). 
                        beginTransaction().addToBackStack("next") 
                        .replace(R.id. container,new SecondFragment()) 
                        .commit(); 

            } 
        }); 
        //Return fragment view 
        return view; 
    } 
}

The second fragment interface class realizes the function and opens the second fragment interface classSecondFragment

 Specific code:

package net.zyt.switch_fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class SecondFragment extends Fragment {


    private Button btnNextFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //获取碎片视图
        View view = inflater.inflate(R.layout.fragment_second, container, false); 
        //Get the control instance through the resource identifier 
        btnNextFragment = view.findViewById(R.id.btn_next_fragment); 
        //Register the click event listener for the button 
        btnNextFragment.setOnClickListener(new View.OnClickListener() { 
            @Override 
            public void onClick(View v) { 
                //Switch to the second fragment 
                getFragmentManager(). 
                        beginTransaction().addToBackStack("next") 
                        .replace(R.id. container, new ThirdFragment()) 
                        .commit(); 

            } 
        }); 
        //Return fragment view 
        return view;
    }}

The third fragment interface class realizes the function and opens three fragment interface classesThirdFragment

Specific code: 

package net.zyt.switch_fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class ThirdFragment extends Fragment {


    private Button btnNextFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //获取碎片视图
        View view = inflater.inflate(R.layout.fragment_third, container, false); 
        //Get the control instance through the resource identifier 
        btnNextFragment = view.findViewById(R.id.btn_next_fragment); 
        //Register the click event listener for the button 
        btnNextFragment.setOnClickListener(new View.OnClickListener() { 
            @Override 
            public void onClick(View v) { 
                //Switch to the second fragment 
                getFragmentManager(). 
                        beginTransaction().addToBackStack("next") 
                        .replace(R.id. container, new FirstFragment()) 
                        .commit(); 

            } 
        }); 
        //Return fragment view 
        return view;
    }}

Start the application to see the effect:

 

optimization:

Every time you switch fragments, you use new to create new fragments, which leads to waste of resources in the process of constantly switching fragments

Create a shard list class

The fragment list class  FragmentListis used to save the fragment objects to be used by the program

 

 

 Specific code:

package net.zyt.switch_fragment;
import androidx.fragment.app.Fragment;
import java.util.ArrayList;
import java.util.List;

public class FragmentList{
    public static List<Fragment> fragments = new ArrayList<>();
}

Modify the main interface class

Save the fragment objects needed by the program in the fragment list class

 Specific code:

package net.zyt.switch_fragment; 

import androidx.appcompat.app.AppCompatActivity; 
import androidx.fragment.app.Fragment; 
import androidx.fragment.app.FragmentManager; 

import android.os.Bundle; 

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        //Use the layout resource file to set the user interface 
        setContentView(R.layout.activity_main); 


        //Get the fragment manager 
        FragmentManager fm=getSupportFragmentManager(); 
        //Create three Fragment, add to fragment list 
        FragmentList.fragments.add(new FirstFragment()); 
        FragmentList.fragments.add(new SecondFragment());
        FragmentList.fragments.add(new ThirdFragment()); 

        //Add the first fragment in the main container 
        fm.beginTransaction().add(R.id.container,FragmentList.fragments.get(0)).commit() ; 

    } 
}

Modify the first fragment interface class

will new SecondFragment()be changed toFragmentList.fragments.get(1)

 

Modify the second fragment interface class

will new ThirdFragment()be changed toFragmentList.fragments.get(2)

 

Modify the third fragment interface class

will new FirstFragment()be changed toFragmentList.fragments.get(0)

 

 Run the program to see the effect:

 

 

Guess you like

Origin blog.csdn.net/hollow_future/article/details/127905900