Fragment

@bingoogolapple 2016-12-21 08:13:54发表于 bingoogolapple/bingoogolapple.github.io Android

不用这种,前后台切换时,每次都会走所有已添加过的 Fragment 的 onStart 和 onPause 方法

@Override
protected void setListener() {
    RxRadioGroup.checkedChanges(mBinding.rgLocationChooseType).subscribe(integer -> {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        Fragment newFragment = null;
        if (mBinding.rgLocationChooseType.getCheckedRadioButtonId() == R.id.rb_location_choose_map) {
            if (mLocationChooseMapFragment == null) {
                mLocationChooseMapFragment = new LocationChooseMapFragment();
                fragmentTransaction.add(R.id.fl_location_choose_content, mLocationChooseMapFragment);
            }
            newFragment = mLocationChooseMapFragment;
        } else if (mBinding.rgLocationChooseType.getCheckedRadioButtonId() == R.id.rb_location_choose_history) {
            if (mLocationChooseHistoryFragment == null) {
                mLocationChooseHistoryFragment = new LocationChooseHistoryFragment();
                fragmentTransaction.add(R.id.fl_location_choose_content, mLocationChooseHistoryFragment);
            }
            newFragment = mLocationChooseHistoryFragment;
        } else {
            if (mLocationChooseOtherFragment == null) {
                mLocationChooseOtherFragment = new LocationChooseOtherFragment();
                fragmentTransaction.add(R.id.fl_location_choose_content, mLocationChooseOtherFragment);
            }
            newFragment = mLocationChooseOtherFragment;
        }
        // 显示新的 fragment
        fragmentTransaction.show(newFragment);

        // 如果之前的 fragment 不为 null,则隐藏之前的 fragment
        if (mCurrentFragment != null) {
            fragmentTransaction.hide(mCurrentFragment);
        }

        mCurrentFragment = newFragment;

        fragmentTransaction.commit();
    });
}