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;
        }
    }

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

猜你喜欢

转载自blog.csdn.net/Leavessilent/article/details/55101032