Android之RadioButton配合Fragment实现懒加载

在Android开发搭建主界面框架的时候,我们一般都会使用RadioButton然后监听点击事件配合FragmentManager来实现主界面的切换。如图,假设我们APP有四个主模块:

这里写图片描述

一般的思路

  • 首先我们需要创建出四个模块的实例
  • 通过getSupportFragmentManager在RadioButton的点击事件里面hide、show对应的Fragment

如果是这种情况,我们的mainActivity里面必须同时持有四个主Fragment的引用,这样很浪费空间。因为用户停留在首页页面时,其他页面的实例就已经全部创建出来了。

那我们能不能在用户点击到哪个页面时我们在创建呢?当然可以,这就是我们今天要说的Fragment的懒加载。

懒加载思路

  • 首先在activity创建的时候,将首页显示出来
// 这里创建一个成员变量记录目前正在显示的Fragment
mShowFragment = new HomeFragment();    
// 这里非常重要,添加Fragment的时候,我们添加对应的TAG,TAG名虽然随意,但尽量使用该Fragment的类名,
getSupportFragmentManager().beginTransaction().add(R.id.container, mShowFragment, HomeFragment.TAG).commit();
  • 创建一个页面切换的方法:

    /**
     * @param tag 标记名
     * @param cls 需要创建的Fragment的类名
     */
    private void switchPage(String tag, Class cls) {
        // 通过此方法我们可以查找在当前容器中是否存在该tag名的Fragment
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
        if (fragment == null) {
            try {
                // 通过反射创建出该类对象
                Fragment instance = (Fragment) cls.newInstance();
                getSupportFragmentManager().beginTransaction().add(
                R.id.container, 
                instance, 
                tag).commit();
                mShowFragment = instance;
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
       getSupportFragmentManager().beginTransaction().hide(mShowFragment).show(fragment).commit();
            mShowFragment = fragment;
        }
    }
  • 最后在RadioButton的监听事件中,我们只需要这么调用:
 public void onClick(View view) {
        switch (view.getId()) {
            case R.id.controller_category:
                switchPage(CategoryFragment.TAG, CategoryFragment.class);
                break;
            case R.id.controller_home:
                switchPage(HomeFragment.TAG, HomeFragment.class);
                break;
            case R.id.controller_mine:
                switchPage(MineFragment.TAG, MineFragment.class);
                break;
            case R.id.controller_live:
                switchPage(LiveFragment.TAG, LiveFragment.class);
                break;
        }
    }

怎么样,是不是特别简洁优雅。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值