对Fragment生命周期的理解以及其与Activity的关联
Fragment生命周期的四種狀態
Fragment和Activity類似,也存在運行狀態、暫停狀態、停止狀態和銷毀狀態。
Fragment的回調函數
Fragment為11個,與比Activity不同的有5個。分別為:
與四種狀態結合,如下圖:
Fragment相當于Activity的一個片段,被包含在Activity中,一個Activity中可含有多個Fragment,一個Fragment也可以附屬在多個Activity上Fragment也可包含Fragment。
結合Viewpage、TabLayout、RecyclerView實現多個Fragment的切換以及頁面的滑動效果
以下為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"><com.google.android.material.tabs.TabLayoutandroid:id="@+id/tabs"android:layout_width="match_parent"android:layout_height="wrap_content" ><com.google.android.material.tabs.TabItemandroid:id="@+id/tabItem_follow"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="關注" /><com.google.android.material.tabs.TabItemandroid:id="@+id/tabItem_recommend"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="推薦" /><com.google.android.material.tabs.TabItemandroid:id="@+id/tabItem_digital"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="數碼" /></com.google.android.material.tabs.TabLayout><androidx.viewpager.widget.ViewPagerandroid:id="@+id/id_page_vp"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1" /></LinearLayout>以下為fragment_main.xml布局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/recycler_view"android:layout_width="match_parent"android:layout_height="match_parent" /><Buttonandroid:id="@+id/close_comment"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_alignParentBottom="true"android:layout_marginBottom="375dp"android:background="#0000"android:visibility="gone"tools:visibility="visible" /><FrameLayoutandroid:id="@+id/comment_frameLayout"android:layout_width="match_parent"android:layout_height="375dp"android:layout_alignParentBottom="true"android:visibility="gone" /> </RelativeLayout>以下為video_data.xml布局文件(RecyclerView所對應的一個item的布局文件)
<?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:id="@+id/line4"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginTop="15dp"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="51dp"android:gravity="center_vertical"android:orientation="horizontal"><FrameLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"><com.example.testapp1.control.RoundImageButtonandroid:id="@+id/imageButton"android:layout_width="50dp"android:layout_height="50dp"android:background="@drawable/cir1"android:scaleType="fitXY" /><com.example.testapp1.control.RoundImageButtonandroid:id="@+id/imageButton1"android:layout_width="15dp"android:layout_height="15dp"android:layout_gravity="bottom|right"android:background="@drawable/cir1" /></FrameLayout><TextViewandroid:id="@+id/tv1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="5dp"android:text="某某某博主"android:textSize="8pt" /><FrameLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"><Buttonandroid:id="@+id/button4"android:layout_width="50dp"android:layout_height="30dp"android:background="#00000000"android:text="+關注"android:textColor="@color/design_default_color_error"android:textSize="6pt" /><Buttonandroid:id="@+id/button44"android:layout_width="50dp"android:layout_height="30dp"android:background="#00000000"android:text="已關注"android:textColor="@android:color/darker_gray"android:textSize="6pt"android:visibility="invisible" /></FrameLayout></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"><TextViewandroid:id="@+id/tv4"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginRight="20dp"android:ellipsize="end"android:maxEms="13"android:maxLines="2"android:text="emmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm"android:textColor="@color/black"android:textSize="10pt" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="40dp"android:gravity="center_vertical"android:orientation="horizontal"><TextViewandroid:id="@+id/tv5"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="25萬次播放"android:textSize="5pt" /><FrameLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="180dp"><ImageButtonandroid:id="@+id/imageButton2"android:layout_width="20dp"android:layout_height="20dp"android:background="@mipmap/detail_sharebar_like"android:visibility="visible" /><ImageButtonandroid:id="@+id/imageButton22"android:layout_width="20dp"android:layout_height="20dp"android:background="@mipmap/detail_sharebar_likehighlighted"android:visibility="invisible" /></FrameLayout><TextViewandroid:id="@+id/tv3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="1dp"android:text="22268"android:textColor="@color/black"android:textSize="6pt" /><ImageButtonandroid:id="@+id/imageButton3"android:layout_width="23dp"android:layout_height="23dp"android:layout_marginLeft="7dp"android:background="@mipmap/comment_immersive_v4_5_white_big"tools:src="@android:drawable/ic_menu_view" /><TextViewandroid:id="@+id/tv6"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="1dp"android:text="268"android:textColor="@color/black"android:textSize="6pt" /><ImageButtonandroid:id="@+id/imageButton4"android:layout_width="23dp"android:layout_height="23dp"android:layout_marginLeft="7dp"android:background="@mipmap/halo_share_icon"tools:src="?attr/actionModeShareDrawable" /></LinearLayout></LinearLayout><VideoViewandroid:id="@+id/video_view"android:layout_width="match_parent"android:layout_height="250dp" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="80dp"android:layout_marginTop="10dp"android:gravity="center_vertical"android:orientation="horizontal"><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/recycler_view1"android:layout_width="match_parent"android:layout_height="match_parent" /></LinearLayout><VideoViewandroid:id="@+id/video_view1"android:layout_width="match_parent"android:layout_height="250dp"android:layout_marginTop="25dp" /> </LinearLayout>以下為MainActivity.java
public class MainActivity extends FragmentActivity {private static final String TAG = "--MainActivity---甘---";private List<Fragment> mFragmentList = new ArrayList<Fragment>();private FragmentAdapter mFragmentAdapter;private ViewPager mPageVp;private FollowVideoFragment mFollowVideoFragment;private RecommendVideoFragment mRecommendVideoFragment;private DigitalVideoFragment mDigitalVideoFragment;@Overrideprotected void onCreate(Bundle savedInstanceState) {Log.i(TAG, "-----------onCreate-------------");super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mPageVp = this.findViewById(R.id.id_page_vp);//綁定viewpage與TabLayoutTabLayout tabLayout = findViewById(R.id.tabs);mPageVp.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mPageVp));init();}private void init() {mFollowVideoFragment = new FollowVideoFragment();mRecommendVideoFragment = new RecommendVideoFragment();mDigitalVideoFragment = new DigitalVideoFragment();mFragmentList.add(mFollowVideoFragment);mFragmentList.add(mRecommendVideoFragment);mFragmentList.add(mDigitalVideoFragment);mFragmentAdapter = new FragmentAdapter(this.getSupportFragmentManager(), mFragmentList);mPageVp.setAdapter(mFragmentAdapter);mPageVp.setCurrentItem(1);}@Overrideprotected void onStart() {super.onStart();Log.i(TAG, "-----------onStart-------------");}@Overrideprotected void onRestart() {super.onRestart();Log.i(TAG, "-----------onRestart-------------");}@Overrideprotected void onResume() {super.onResume();Log.i(TAG, "-----------onResume-------------");}@Overrideprotected void onPause() {super.onPause();Log.i(TAG, "-----------onPause-------------");}@Overrideprotected void onStop() {super.onStop();Log.i(TAG, "-----------onStop-------------");}@Overrideprotected void onDestroy() {super.onDestroy();Log.i(TAG, "-----------onDestroy-------------");}}以下為FollowVideoFragment.java
public class FollowVideoFragment extends Fragment {private static final String TAG = "--FollowVideoFragment---甘---";@Overridepublic void onAttach(@NonNull Context context) {Log.i(TAG,"--------onAttach---------");super.onAttach(context);}@Overridepublic void onCreate(@Nullable Bundle savedInstanceState) {Log.i(TAG, "--------onCreate---------");super.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {Log.i(TAG, "--------onCreateView---------");super.onCreateView(inflater, container, savedInstanceState);View videoView = inflater.inflate(R.layout.fragment_main, container, false);//此處通過RecyclerView實現頁面的滑動效果RecyclerView recyclerView = videoView.findViewById(R.id.recycler_view);recyclerView.setHasFixedSize(true);LinearLayoutManager layoutManager = new LinearLayoutManager(videoView.getContext());layoutManager.setOrientation(LinearLayoutManager.VERTICAL);recyclerView.setLayoutManager(layoutManager);recyclerView.setAdapter(adapter);return videoView;}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {Log.i(TAG, "--------onActivityCreated---------");super.onActivityCreated(savedInstanceState);}@Overridepublic void onStart() {Log.i(TAG, "--------onStart---------");super.onStart();}@Overridepublic void onResume() {Log.i(TAG, "--------onResume---------");super.onResume();}@Overridepublic void onPause() {Log.i(TAG, "--------onPause---------");super.onPause();}@Overridepublic void onStop() {Log.i(TAG, "--------onStop---------");super.onStop();}@Overridepublic void onDestroyView() {Log.i(TAG, "--------onDestroyView---------");super.onDestroyView();}@Overridepublic void onDestroy() {Log.i(TAG, "--------onDestroy---------");super.onDestroy();}@Overridepublic void onDetach() {Log.i(TAG, "--------onDetach---------");super.onDetach();}其他兩個Fragment的代碼和FollowVideoFragment幾乎一樣,此處不在列出。此處三個Fragment對應同一Adapter(適配器),每一個Fragment都要有與其對應的適配器。本人在Adapter后還建立了holder用于對應一個item的綁定數據。
VideoAdapter.java
VideoViewHolder.java,因本人demo的實體類數據不同且需放同一list中,并為綁定數據方便,實現多態,封裝了一個BaseHolder的方法,讀者可將繼承改為RecyclerView.ViewHolder
public class VideoViewHolder extends RecyclerView.ViewHolder<VideoData> {private VideoView videoView;TextView personName;//RoundImageButton與RoundImageButton是自定義控件RoundImageButton personHeadId;RoundImageButton personLevelid;TextView personIntroduction;TextView videoNumber;TextView goodNumber;TextView commentNumber;VideoView video1;VideoView video2;RecyclerView recyclerView;private Context mContext;@Overridepublic void bindData(VideoData videoData) {personName.setText(videoData.getName());personHeadId.setImageResource(videoData.getHeadId());personLevelid.setImageResource(videoData.getLevelId());personIntroduction.setText(videoData.getIntroduction());videoNumber.setText(videoData.getVideoNumber());goodNumber.setText(videoData.getGoodNumber());commentNumber.setText(videoData.getCommentNumber());itemView.findViewById(R.id.imageButton4).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent = new Intent(view.getContext(), NextActivity.class);view.getContext().startActivity(intent);}});}public VideoViewHolder(View view, Context mContext) {super(view);this.mContext = mContext;personName = view.findViewById(R.id.tv1);personHeadId = view.findViewById(R.id.imageButton);personLevelid = view.findViewById(R.id.imageButton1);personIntroduction = view.findViewById(R.id.tv4);videoNumber = view.findViewById(R.id.tv5);goodNumber = view.findViewById(R.id.tv3);commentNumber = view.findViewById(R.id.tv6);video1 = view.findViewById(R.id.video_view);video2 = view.findViewById(R.id.video_view1);recyclerView = view.findViewById(R.id.recycler_view1);}}tips:以上代碼可能有些繞,簡單來說就是Activity包含Fragment,又因為想實現滑動效果,Fragment中包含了RecyclerView,Adapter作為適配器為RecyclerView創建item對應的view并可綁定數據(holder的代碼可以放入其中),holder為item綁定數據。
通過打Log觀察一個或多個Fragment的生命周期變化
一個Fragment
運行app:
按home鍵:
鎖屏:
按返回鍵:
多個Fragment
tablayout中默認選中中間的Fragment,此時運行APP:
滑動至FollowVideoFragment:
從FollowVideoFragment滑動至RecommendVideoFragment再滑動至DigitalVideoFragment:
在DigitalVideoFragment進行home鍵操作:
回到APP,在DigitalVideoFragment再進行鎖屏鍵操作:
解鎖,再按back鍵:
Activity的Fragment和另一個Activity之間的切換觀察Fragment的生命周期
三個Fragment的生命周期變化:
MainActivity與另一個Activity的變化:
tips:Viewpage、TabLayout、RecyclerView將在筆者后續博客中。
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的对Fragment生命周期的理解以及其与Activity的关联的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android Activity的理解
- 下一篇: JAVA基础中容易踩坑的知识点