美文网首页
Fragment 生命周期

Fragment 生命周期

作者: 这个杀手不太累 | 来源:发表于2017-09-07 10:34 被阅读9次
    activity_fragment_lifecycle.png
    • 在生命周期方法中添加打印
    public class LifecycleFragment extends Fragment {
    
        public static final String TAG = "LifecycleFragment";
    
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            Log.d(TAG, "onAttach");
        }
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.d(TAG, "onCreate");
        }
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            Log.d(TAG, "onCreateView");
            View view = inflater.inflate(R.layout.lifecycle_fragment, container, false);
            return view;
        }
    
        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            Log.d(TAG, "onActivityCreated");
        }
    
        @Override
        public void onStart() {
            super.onStart();
            Log.d(TAG, "onStart");
        }
    
        @Override
        public void onResume() {
            super.onResume();
            Log.d(TAG, "onResume");
        }
    
        @Override
        public void onPause() {
            super.onPause();
            Log.d(TAG, "onPause");
        }
    
        @Override
        public void onStop() {
            super.onStop();
            Log.d(TAG, "onStop");
        }
    
        @Override
        public void onDestroyView() {
            super.onDestroyView();
            Log.d(TAG, "onDestroyView");
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.d(TAG, "onDestroy");
        }
    
        @Override
        public void onDetach() {
            super.onDetach();
            Log.d(TAG, "onDetach");
        }
    }
    
    • 布局文件中添加这个Fragment
    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/news_title_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
    
        <fragment
            android:id="@+id/news_title_fragment"
            android:name="com.example.fragmenttest.LifecycleFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
    
    • 运行程序观察打印
    run_fragmenttest.png
    • 点击back键后打印
    back_fragment.png

    相关文章

      网友评论

          本文标题:Fragment 生命周期

          本文链接:https://www.haomeiwen.com/subject/ffobjxtx.html