2020-3-24 EShop代码分析-main activity
Posted hu14god
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2020-3-24 EShop代码分析-main activity相关的知识,希望对你有一定的参考价值。
// 当前正在显示的Fragment
private Fragment mCurrentFragment;
// 主页面只负责四个Fragment的切换, 没有业务逻辑的处理.
//四个Fragment的监听点击事件
@Override public void onTabSelected(@IdRes int tabId) {
switch (tabId) {
case R.id.tab_home:
if (mHomeFragment == null) mHomeFragment = HomeFragment.newInstance();
switchFragment(mHomeFragment);
break;
case R.id.tab_category:
if (mCategoryFragment == null) mCategoryFragment = CategoryFragment.newInstance();
switchFragment(mCategoryFragment);
break;
case R.id.tab_cart:
if (mCartFragment == null) mCartFragment = CartFragment.newInstance();
switchFragment(mCartFragment);
break;
case R.id.tab_mine:
if (mMineFragment == null) mMineFragment = MineFragment.newInstance();
switchFragment(mMineFragment);
break;
default:
throw new UnsupportedOperationException("Illegal branch!");
}
}
// 如果不是在HomeFragment, 则按返回键回到HomeFragment
@Override public void onBackPressed() {
if (mCurrentFragment != mHomeFragment) {
bottomBar.selectTabWithId(R.id.tab_home);
return;
}
// 将Activity所在的Task移到后台, 而不是finish此Activity
moveTaskToBack(true);
}
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onEvent(CartEvent event) {
// 如果购物车数据发生变更, 需要更新BottomBar的角标
if (UserManager.getInstance().hasCart()) {
int total = UserManager.getInstance().getCartBill().getGoodsCount();
bottomBar.getTabAtPosition(2).setBadgeCount(total);
} else {
bottomBar.getTabAtPosition(2).removeBadge();
}
}
/**
* 首页4个Fragment切换, 使用hide和show, 而不是replace.
*
* @param target 要显示的目标Fragment.
*/
private void switchFragment(Fragment target) {
if (mCurrentFragment == target) return;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (mCurrentFragment != null) {
// 隐藏当前正在显示的Fragment
transaction.hide(mCurrentFragment);
}
if (target.isAdded()) {
// 如果目标Fragment已经添加过, 就显示它
transaction.show(target);
} else {
// 否则直接添加该Fragment
transaction.add(R.id.layout_container, target, target.getClass().getName());
}
transaction.commit();
mCurrentFragment = target;
}
// 找回FragmentManager中存储的Fragment
private void retrieveFragments() {
FragmentManager manager = getSupportFragmentManager();
mHomeFragment = (HomeFragment) manager.findFragmentByTag(HomeFragment.class.getName());
mCategoryFragment = (CategoryFragment) manager
.findFragmentByTag(CategoryFragment.class.getName());
mCartFragment = (CartFragment) manager.findFragmentByTag(CartFragment.class.getName());
mMineFragment = (MineFragment) manager.findFragmentByTag(MineFragment.class.getName());
}
以上是关于2020-3-24 EShop代码分析-main activity的主要内容,如果未能解决你的问题,请参考以下文章
Vue+Spring Boot+MyBatis实现Eshop电子商城(持续更新)
无法创建类型为“EShop.ClassLibrary.ProductType”的常量值。此上下文仅支持原始类型或枚举类型