组件 -- Fragment -- 1

一、概念

作为Activity界面的一部分,Fragment的存在必须依附于Activity,并且与Activity一样,拥有自己的生命周期,同时处理用户的交互动作。同一个Activity可以有一个或多个Fragment作为界面内容,并且可以动态添加、删除Fragment,灵活控制UI内容,也可以用来解决部分屏幕适配问题。

另外,support v4包中也提供了Fragment,兼容Android 3.0之前的系统(当然,现在3.0之前的系统在市场上已经很少见了,可以不予考虑),使用兼容包需要注意两点:

  • Activity必须继承自FragmentActivity。
  • 使用getSupportFragmentManager()方法获取FragmentManager对象。

二、生命周期

Fragment生命周期

三、创建实例

public static OneFragment newInstance(int args){
    OneFragment oneFragment = new OneFragment();

    Bundle bundle = new Bundle();
    bundle.putInt("someArgs", args);

    oneFragment.setArguments(bundle);
    return oneFragment;
}

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

    Bundle bundle = getArguments();
    int args = bundle.getInt("someArgs");
}

四、Activity嵌入Fragment

Activity嵌入Fragment分为布局静态嵌入和代码动态嵌入两种。
1.布局静态嵌入

//build.gradle(project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

//build.gradle(module)
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.0"
    defaultConfig {
        applicationId "com.example.sourcecodetest"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

//AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sourcecodetest">
    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:launchMode="standard">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

//fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is one fragment layout"/>
</LinearLayout>

//OneFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class OneFragment extends Fragment {
    private static final String TAG = "OneFragment";

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        Log.d(TAG, "zwm, onInflate");
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "zwm, onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "zwm, onCreate");
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateView");
        View contentView = inflater.inflate(R.layout.fragment_main, null);
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "zwm, onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "zwm, onDetach");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Log.d(TAG, "zwm, onCreateOptionsMenu");
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        Log.d(TAG, "zwm, onPrepareOptionsMenu");
    }
}

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <fragment
        android:id="@+id/fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.example.sourcecodetest.OneFragment"/>
</LinearLayout>

//MainActivity
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "zwm, onCreate");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "zwm, onNewIntent: " + intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }
}

//输出log
2020-01-19 11:27:41.440 30794-30794/com.example.sourcecodetest D/MyApplication: zwm, onCreate
2020-01-19 11:27:41.985 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onInflate
2020-01-19 11:27:41.985 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onAttach
2020-01-19 11:27:41.985 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onCreate
2020-01-19 11:27:41.990 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onCreateView
2020-01-19 11:27:41.998 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onViewCreated
2020-01-19 11:27:41.998 30794-30794/com.example.sourcecodetest D/MainActivity: zwm, onCreate
2020-01-19 11:27:42.054 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onActivityCreated
2020-01-19 11:27:42.055 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onStart
2020-01-19 11:27:42.056 30794-30794/com.example.sourcecodetest D/MainActivity: zwm, onStart
2020-01-19 11:27:43.169 30794-30794/com.example.sourcecodetest D/MainActivity: zwm, onResume
2020-01-19 11:27:43.170 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onResume
2020-01-19 11:27:43.385 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onCreateOptionsMenu
2020-01-19 11:27:43.386 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 11:27:43.388 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 11:27:50.909 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onPause
2020-01-19 11:27:50.909 30794-30794/com.example.sourcecodetest D/MainActivity: zwm, onPause
2020-01-19 11:27:51.732 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onStop
2020-01-19 11:27:51.732 30794-30794/com.example.sourcecodetest D/MainActivity: zwm, onStop
2020-01-19 11:27:51.760 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onDestroyView
2020-01-19 11:27:51.763 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onDestroy
2020-01-19 11:27:51.764 30794-30794/com.example.sourcecodetest D/OneFragment: zwm, onDetach
2020-01-19 11:27:51.765 30794-30794/com.example.sourcecodetest D/MainActivity: zwm, onDestroy

2.代码动态嵌入

//fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is one fragment layout"/>
</LinearLayout>

//OneFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class OneFragment extends Fragment {
    private static final String TAG = "OneFragment";

    public static OneFragment newInstance(int args){
        Log.d(TAG, "zwm, newInstance, args: " + args);
        OneFragment oneFragment = new OneFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("someArgs", args);
        oneFragment.setArguments(bundle);
        return oneFragment;
    }

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        Log.d(TAG, "zwm, onInflate");
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "zwm, onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "zwm, onCreate");
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        int args = -1;
        if(bundle != null) {
            args = bundle.getInt("someArgs");
        }
        Log.d(TAG, "zwm, onCreate, args: " + args);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateView");
        View contentView = inflater.inflate(R.layout.fragment_main, null);
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "zwm, onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "zwm, onDetach");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Log.d(TAG, "zwm, onCreateOptionsMenu");
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        Log.d(TAG, "zwm, onPrepareOptionsMenu");
    }
}

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
    
//MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "zwm, onCreate");

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.fragment_container, OneFragment.newInstance(99));
        ft.commit();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "zwm, onNewIntent: " + intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }
}

//输出log
2020-01-19 11:43:24.932 4176-4176/com.example.sourcecodetest D/MyApplication: zwm, onCreate
2020-01-19 11:43:25.354 4176-4176/com.example.sourcecodetest D/MainActivity: zwm, onCreate
2020-01-19 11:43:25.359 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, newInstance, args: 99
2020-01-19 11:43:25.369 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onAttach
2020-01-19 11:43:25.369 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onCreate
2020-01-19 11:43:25.369 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onCreate, args: 99
2020-01-19 11:43:25.370 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onCreateView
2020-01-19 11:43:25.378 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onViewCreated
2020-01-19 11:43:25.378 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onActivityCreated
2020-01-19 11:43:25.378 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onStart
2020-01-19 11:43:25.379 4176-4176/com.example.sourcecodetest D/MainActivity: zwm, onStart
2020-01-19 11:43:25.382 4176-4176/com.example.sourcecodetest D/MainActivity: zwm, onResume
2020-01-19 11:43:25.383 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onResume
2020-01-19 11:43:25.522 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onCreateOptionsMenu
2020-01-19 11:43:25.522 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 11:43:25.524 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 11:43:30.407 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onPause
2020-01-19 11:43:30.407 4176-4176/com.example.sourcecodetest D/MainActivity: zwm, onPause
2020-01-19 11:43:31.066 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onStop
2020-01-19 11:43:31.066 4176-4176/com.example.sourcecodetest D/MainActivity: zwm, onStop
2020-01-19 11:43:31.070 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onDestroyView
2020-01-19 11:43:31.076 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onDestroy
2020-01-19 11:43:31.076 4176-4176/com.example.sourcecodetest D/OneFragment: zwm, onDetach
2020-01-19 11:43:31.078 4176-4176/com.example.sourcecodetest D/MainActivity: zwm, onDestroy

这两种嵌入方式对应的Fragment生命周期略有不同,从生命周期图中可以看出。相比布局静态嵌入方式,代码动态嵌入方式更为常用,毕竟后者能够实现灵活控制多个Fragment,动态改变Activity中的内容。

五、Fragment嵌套Fragment

在Activity嵌入Fragment时,需要使用FragmentManager,通过Activity提供的getFragmentManager()方法即可获取,用于管理Activity里面嵌入的所有一级Fragment。然而有时候,我们会在Fragment里面继续嵌套二级甚至三级Fragment,即Activity嵌套多级Fragment,此时在Fragment里管理子Fragment时,也需要使用到FragmentManager,但是一定要使用getChildFragmentManager()方法获取FragmentManager对象。

//fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sub_fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
    
//OneFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class OneFragment extends Fragment {
    private static final String TAG = "OneFragment";

    public static OneFragment newInstance(int args){
        Log.d(TAG, "zwm, newInstance, args: " + args);
        OneFragment oneFragment = new OneFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("someArgs", args);
        oneFragment.setArguments(bundle);
        return oneFragment;
    }

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        Log.d(TAG, "zwm, onInflate");
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "zwm, onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "zwm, onCreate");
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        int args = -1;
        if(bundle != null) {
            args = bundle.getInt("someArgs");
        }
        Log.d(TAG, "zwm, onCreate, args: " + args);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateView");
        View contentView = inflater.inflate(R.layout.fragment_main, null);

        FragmentManager fm = getChildFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.sub_fragment_container, SubFragment.newInstance(9999));
        ft.commit();
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "zwm, onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "zwm, onDetach");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Log.d(TAG, "zwm, onCreateOptionsMenu");
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        Log.d(TAG, "zwm, onPrepareOptionsMenu");
    }
}

//fragment_sub.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is sub fragment layout"/>
</LinearLayout>

//SubFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class SubFragment extends Fragment {
    private static final String TAG = "SubFragment";

    public static SubFragment newInstance(int args){
        Log.d(TAG, "zwm, newInstance, args: " + args);
        SubFragment subFragment = new SubFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("someArgs", args);
        subFragment.setArguments(bundle);
        return subFragment;
    }

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        Log.d(TAG, "zwm, onInflate");
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "zwm, onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "zwm, onCreate");
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        int args = -1;
        if(bundle != null) {
            args = bundle.getInt("someArgs");
        }
        Log.d(TAG, "zwm, onCreate, args: " + args);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateView");
        View contentView = inflater.inflate(R.layout.fragment_sub, null);
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "zwm, onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "zwm, onDetach");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Log.d(TAG, "zwm, onCreateOptionsMenu");
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        Log.d(TAG, "zwm, onPrepareOptionsMenu");
    }
}

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
    
//MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "zwm, onCreate");

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.fragment_container, OneFragment.newInstance(99));
        ft.commit();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "zwm, onNewIntent: " + intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }
}

//输出log
2020-01-19 13:33:24.973 13499-13499/com.example.sourcecodetest D/MyApplication: zwm, onCreate
2020-01-19 13:33:25.184 13499-13499/com.example.sourcecodetest D/MainActivity: zwm, onCreate
2020-01-19 13:33:25.189 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, newInstance, args: 99
2020-01-19 13:33:25.199 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onAttach
2020-01-19 13:33:25.200 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onCreate
2020-01-19 13:33:25.200 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onCreate, args: 99
2020-01-19 13:33:25.201 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onCreateView
2020-01-19 13:33:25.202 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, newInstance, args: 9999
2020-01-19 13:33:25.203 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onViewCreated
2020-01-19 13:33:25.203 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onActivityCreated
2020-01-19 13:33:25.203 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onAttach
2020-01-19 13:33:25.204 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onCreate
2020-01-19 13:33:25.204 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onCreate, args: 9999
2020-01-19 13:33:25.204 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onCreateView
2020-01-19 13:33:25.211 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onViewCreated
2020-01-19 13:33:25.211 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onActivityCreated
2020-01-19 13:33:25.212 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onStart
2020-01-19 13:33:25.212 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onStart
2020-01-19 13:33:25.213 13499-13499/com.example.sourcecodetest D/MainActivity: zwm, onStart
2020-01-19 13:33:25.215 13499-13499/com.example.sourcecodetest D/MainActivity: zwm, onResume
2020-01-19 13:33:25.216 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onResume
2020-01-19 13:33:25.216 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onResume
2020-01-19 13:33:25.334 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onCreateOptionsMenu
2020-01-19 13:33:25.334 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onCreateOptionsMenu
2020-01-19 13:33:25.335 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 13:33:25.335 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onPrepareOptionsMenu
2020-01-19 13:33:25.337 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 13:33:25.337 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onPrepareOptionsMenu
2020-01-19 13:33:29.167 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onPause
2020-01-19 13:33:29.168 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onPause
2020-01-19 13:33:29.168 13499-13499/com.example.sourcecodetest D/MainActivity: zwm, onPause
2020-01-19 13:33:29.771 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onStop
2020-01-19 13:33:29.771 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onStop
2020-01-19 13:33:29.772 13499-13499/com.example.sourcecodetest D/MainActivity: zwm, onStop
2020-01-19 13:33:29.782 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onDestroyView
2020-01-19 13:33:29.786 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onDestroyView
2020-01-19 13:33:29.787 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onDestroy
2020-01-19 13:33:29.788 13499-13499/com.example.sourcecodetest D/SubFragment: zwm, onDetach
2020-01-19 13:33:29.790 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onDestroy
2020-01-19 13:33:29.790 13499-13499/com.example.sourcecodetest D/OneFragment: zwm, onDetach
2020-01-19 13:33:29.791 13499-13499/com.example.sourcecodetest D/MainActivity: zwm, onDestroy

六、FragmentTransaction关键方法

  • add()系列:添加Fragment到Activity界面中。
  • remove():移除Activity中的指定Fragment。
  • replace()系列:通过内部调用remove()和add()完成Fragment的修改。
  • hide()和show():隐藏和显示Activity中的Fragment。
  • addToBackStack():添加当前事务到回退栈中,即当按下返回键时,界面回归到当前事物状态。
  • commit():提交事务,所有通过上述方法对 Fragment 的改动都必须通过调用commit()方法完成提交。
//fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is one fragment layout"/>
</LinearLayout>

//OneFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class OneFragment extends Fragment {
    private static final String TAG = "OneFragment";

    public static OneFragment newInstance(int args){
        Log.d(TAG, "zwm, newInstance, args: " + args);
        OneFragment oneFragment = new OneFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("someArgs", args);
        oneFragment.setArguments(bundle);
        return oneFragment;
    }

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        Log.d(TAG, "zwm, onInflate");
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "zwm, onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "zwm, onCreate");
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        int args = -1;
        if(bundle != null) {
            args = bundle.getInt("someArgs");
        }
        Log.d(TAG, "zwm, onCreate, args: " + args);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateView");
        View contentView = inflater.inflate(R.layout.fragment_main, null);
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "zwm, onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "zwm, onDetach");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Log.d(TAG, "zwm, onCreateOptionsMenu");
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        Log.d(TAG, "zwm, onPrepareOptionsMenu");
    }
}

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
    
//MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private OneFragment mFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "zwm, onCreate");

        mFragment = OneFragment.newInstance(99);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.fragment_container, mFragment);
        ft.commit();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "zwm, test hide");
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.hide(mFragment);
                ft.commit();

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "zwm, test show");
                        FragmentManager fm = getSupportFragmentManager();
                        FragmentTransaction ft = fm.beginTransaction();
                        ft.show(mFragment);
                        ft.commit();
                    }
                }, 5000);
            }
        }, 5000);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "zwm, onNewIntent: " + intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }
}

//输出log
2020-01-19 13:53:47.733 19874-19874/com.example.sourcecodetest D/MyApplication: zwm, onCreate
2020-01-19 13:53:48.048 19874-19874/com.example.sourcecodetest D/MainActivity: zwm, onCreate
2020-01-19 13:53:48.052 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, newInstance, args: 99
2020-01-19 13:53:48.420 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onAttach
2020-01-19 13:53:48.421 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onCreate
2020-01-19 13:53:48.421 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onCreate, args: 99
2020-01-19 13:53:48.422 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onCreateView
2020-01-19 13:53:48.431 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onViewCreated
2020-01-19 13:53:48.431 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onActivityCreated
2020-01-19 13:53:48.431 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onStart
2020-01-19 13:53:48.433 19874-19874/com.example.sourcecodetest D/MainActivity: zwm, onStart
2020-01-19 13:53:48.553 19874-19874/com.example.sourcecodetest D/MainActivity: zwm, onResume
2020-01-19 13:53:48.554 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onResume
2020-01-19 13:53:49.241 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onCreateOptionsMenu
2020-01-19 13:53:49.241 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 13:53:49.243 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 13:53:53.062 19874-19874/com.example.sourcecodetest D/MainActivity: zwm, test hide
2020-01-19 13:53:58.070 19874-19874/com.example.sourcecodetest D/MainActivity: zwm, test show
2020-01-19 13:53:58.080 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onCreateOptionsMenu
2020-01-19 13:53:58.080 19874-19874/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu

七、BackStack(回退栈)

通过addToBackStack()保存当前事务,当用户按下返回键时,如果回退栈中保存有之前的事务,便会执行事务回退,而不是finish掉当前Activity。

//fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is one fragment layout"/>
</LinearLayout>

//OneFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class OneFragment extends Fragment {
    private static final String TAG = "OneFragment";

    public static OneFragment newInstance(int args){
        Log.d(TAG, "zwm, newInstance, args: " + args);
        OneFragment oneFragment = new OneFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("someArgs", args);
        oneFragment.setArguments(bundle);
        return oneFragment;
    }

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        Log.d(TAG, "zwm, onInflate");
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "zwm, onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "zwm, onCreate");
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        int args = -1;
        if(bundle != null) {
            args = bundle.getInt("someArgs");
        }
        Log.d(TAG, "zwm, onCreate, args: " + args);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateView");
        View contentView = inflater.inflate(R.layout.fragment_main, null);
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "zwm, onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "zwm, onDetach");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Log.d(TAG, "zwm, onCreateOptionsMenu");
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        Log.d(TAG, "zwm, onPrepareOptionsMenu");
    }
}

//fragment_sub.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is sub fragment layout"/>
</LinearLayout>

//SubFragment
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class SubFragment extends Fragment {
    private static final String TAG = "SubFragment";

    public static SubFragment newInstance(int args){
        Log.d(TAG, "zwm, newInstance, args: " + args);
        SubFragment subFragment = new SubFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("someArgs", args);
        subFragment.setArguments(bundle);
        return subFragment;
    }

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        Log.d(TAG, "zwm, onInflate");
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "zwm, onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "zwm, onCreate");
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        int args = -1;
        if(bundle != null) {
            args = bundle.getInt("someArgs");
        }
        Log.d(TAG, "zwm, onCreate, args: " + args);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onCreateView");
        View contentView = inflater.inflate(R.layout.fragment_sub, null);
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "zwm, onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "zwm, onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "zwm, onDetach");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        Log.d(TAG, "zwm, onCreateOptionsMenu");
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        Log.d(TAG, "zwm, onPrepareOptionsMenu");
    }
}

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
    
//MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private OneFragment mOneFragment;
    private SubFragment mSubFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "zwm, onCreate");

        mOneFragment = OneFragment.newInstance(99);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.fragment_container, mOneFragment);
        ft.commit();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "zwm, test addToBackStack");
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.hide(mOneFragment); //注意:这里使用了hide()方法,而不是replace()方法,因为我们当然希望用户返回上一步操作时,之前设置的内容不会消失。
                if(mSubFragment == null) {
                    mSubFragment = SubFragment.newInstance(9999);
                    ft.add(R.id.fragment_container, mSubFragment);
                } else {
                    ft.show(mSubFragment);
                }
                ft.addToBackStack(null);
                ft.commit();
            }
        }, 5000);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "zwm, onNewIntent: " + intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "zwm, onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "zwm, onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "zwm, onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "zwm, onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "zwm, onDestroy");
    }
}

//输出log
2020-01-19 14:02:02.112 24779-24779/com.example.sourcecodetest D/MyApplication: zwm, onCreate
2020-01-19 14:02:02.712 24779-24779/com.example.sourcecodetest D/MainActivity: zwm, onCreate
2020-01-19 14:02:02.716 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, newInstance, args: 99
2020-01-19 14:02:02.818 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onAttach
2020-01-19 14:02:02.818 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onCreate
2020-01-19 14:02:02.819 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onCreate, args: 99
2020-01-19 14:02:02.819 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onCreateView
2020-01-19 14:02:02.830 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onViewCreated
2020-01-19 14:02:02.830 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onActivityCreated
2020-01-19 14:02:02.830 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onStart
2020-01-19 14:02:02.831 24779-24779/com.example.sourcecodetest D/MainActivity: zwm, onStart
2020-01-19 14:02:02.904 24779-24779/com.example.sourcecodetest D/MainActivity: zwm, onResume
2020-01-19 14:02:02.905 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onResume
2020-01-19 14:02:03.124 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onCreateOptionsMenu
2020-01-19 14:02:03.124 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 14:02:03.126 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 14:02:07.723 24779-24779/com.example.sourcecodetest D/MainActivity: zwm, test addToBackStack
2020-01-19 14:02:07.724 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, newInstance, args: 9999
2020-01-19 14:02:07.726 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onAttach
2020-01-19 14:02:07.726 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onCreate
2020-01-19 14:02:07.726 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onCreate, args: 9999
2020-01-19 14:02:07.729 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onCreateView
2020-01-19 14:02:07.742 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onViewCreated
2020-01-19 14:02:07.742 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onActivityCreated
2020-01-19 14:02:07.743 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onStart
2020-01-19 14:02:07.743 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onResume
2020-01-19 14:02:07.749 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onCreateOptionsMenu
2020-01-19 14:02:07.749 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onPrepareOptionsMenu
2020-01-19 14:02:16.180 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onPause //按下返回键,移除SubFragment并回到OneFragment
2020-01-19 14:02:16.181 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onStop
2020-01-19 14:02:16.181 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onDestroyView
2020-01-19 14:02:16.185 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onDestroy
2020-01-19 14:02:16.185 24779-24779/com.example.sourcecodetest D/SubFragment: zwm, onDetach
2020-01-19 14:02:16.195 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onCreateOptionsMenu
2020-01-19 14:02:16.196 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onPrepareOptionsMenu
2020-01-19 14:02:25.031 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onPause //再次按下返回键,移除OneFragment并退出MainActivity
2020-01-19 14:02:25.032 24779-24779/com.example.sourcecodetest D/MainActivity: zwm, onPause
2020-01-19 14:02:25.657 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onStop
2020-01-19 14:02:25.657 24779-24779/com.example.sourcecodetest D/MainActivity: zwm, onStop
2020-01-19 14:02:25.662 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onDestroyView
2020-01-19 14:02:25.664 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onDestroy
2020-01-19 14:02:25.664 24779-24779/com.example.sourcecodetest D/OneFragment: zwm, onDetach
2020-01-19 14:02:25.665 24779-24779/com.example.sourcecodetest D/MainActivity: zwm, onDestroy
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,254评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,875评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,682评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,896评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,015评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,152评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,208评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,962评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,388评论 1 304
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,700评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,867评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,551评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,186评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,901评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,142评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,689评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,757评论 2 351

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,900评论 25 707
  • Fragment 描述:   翻译可以译为:碎片、片段,Android 3.0开始引入fragments 的概念;...
    Lost_Robot阅读 1,688评论 0 11
  • Fragment称为Android中的碎片,类似Activity,能够包含Button、Text等其他基本组件.不...
    uniapp阅读 536评论 0 1
  • 前言 Fragment想必大家不陌生吧,在日常开发中,对于Fragment的使用也很频繁,现在主流的APP中,基本...
    斜杠时光阅读 2,577评论 4 22
  • 图文/南桑阿莉 天气:晴 拍摄地点:上海顾村公园 拍摄时间:2018年3月26日 人物:我和好闺蜜(王清艳) 心情...
    南桑阿莉阅读 639评论 9 11