Fragment 使用 replace 的方式实现切换 以及切换的时候Fragment 生命周期
生活随笔
收集整理的這篇文章主要介紹了
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 生命周期的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 英雄的黎明是谁写的呢?
- 下一篇: ViewPager 实现界面加载不同的数