日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Fragment 使用 replace 的方式实现切换 以及切换的时候Fragment 生命周期

發布時間:2023/11/27 生活经验 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Fragment 使用 replace 的方式实现切换 以及切换的时候Fragment 生命周期 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

這個主要代碼在activity里面 如下

public class ReplaceActivity extends AppCompatActivity implements View.OnClickListener {private HpFragment hpFragment;private FilmFragment filmFragment;private TextView hpText;private TextView filmText;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.replace_activity_layout);hpText = findViewById(R.id.hp_text);hpText.setOnClickListener(this);filmText = findViewById(R.id.film_text);filmText.setOnClickListener(this);initTab(0);}private void initTab(int i) {//開啟事務,fragment的控制是由事務來實現的FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();clearSelection();switch (i) {case 0:hpText.setTextColor(Color.RED);if (hpFragment == null) {hpFragment = new HpFragment();}transaction.replace(R.id.content, hpFragment);break;case 1:filmText.setTextColor(Color.RED);if (filmFragment == null) {filmFragment = new FilmFragment();}transaction.replace(R.id.content, filmFragment);break;}transaction.commitAllowingStateLoss();}private void clearSelection() {hpText.setTextColor(Color.BLACK);filmText.setTextColor(Color.BLACK);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.hp_text:initTab(0);hpText.setTextColor(Color.RED);filmText.setTextColor(Color.BLACK);break;case R.id.film_text:initTab(1);hpText.setTextColor(Color.BLACK);filmText.setTextColor(Color.RED);break;}}
}

fragment 的生命周期,當第一次進來的時候默認fragment的生命周期

當切換fragment 新的fragment 的生命周期和上一個幾面的第一次進來的時候相同都會onAttach到onResume

切換之后的fragment的生命周期

總體來說就是fragment 使用replace 來切換的時候使用 顯示的時候會onAttach到onResume ,切換之后會onPause 到 onDetach

demo 地址

?

?

?

總結

以上是生活随笔為你收集整理的Fragment 使用 replace 的方式实现切换 以及切换的时候Fragment 生命周期的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。