设置Fragment的显示与隐藏

本文介绍了一种在Android应用中优化Fragment切换的方法,通过显示与隐藏而非每次都重新创建Fragment来节省资源。这种方法避免了频繁的网络请求和代码重复执行,提高了用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用replace每次都要创建一个fragment去替换到布局里面去,每次都要把fragment里面的代码都走一遍,如果是有很多数据的网络请求,每次都要去请求一遍,很耗时间和流量,解决的办法就是用fragment的显示与隐藏 

//设置Fragment
private void setFragment(int dex) {
    //开启一个事务
    FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();

    if (homeFragment != null) {
        beginTransaction.hide(homeFragment);
    }
    if (typeFragment != null) {
        beginTransaction.hide(typeFragment);
    }
    if (findFragment != null) {
        beginTransaction.hide(findFragment);
    }
    if (shopFragment != null) {
        beginTransaction.hide(shopFragment);
    }
    if (myFragment != null) {
        beginTransaction.hide(myFragment);
    }

    switch (dex) {
        case 0:
            if (homeFragment == null) {
                homeFragment = new HomeFragment();
                //加入事物
                beginTransaction.add(R.id.frame, homeFragment);
            } else {
                //否则就显示
                beginTransaction.show(homeFragment);
            }
            break;

        case 1:
            if (typeFragment == null) {
                typeFragment = new TypeFragment();
                //加入事物
                beginTransaction.add(R.id.frame, typeFragment);
            } else {
                //否则就显示
                beginTransaction.show(typeFragment);
            }
            break;

        case 2:
            if (findFragment == null) {
                findFragment = new FindFragment();
                //加入事物
                beginTransaction.add(R.id.frame, findFragment);
            } else {
                //否则就显示
                beginTransaction.show(findFragment);
            }
            break;

        case 3:
            if (shopFragment == null) {
                shopFragment = new ShopFragment();
                //加入事物
                beginTransaction.add(R.id.frame, shopFragment);
            } else {
                //否则就显示
                beginTransaction.show(shopFragment);
            }
            break;

        case 4:
            if (myFragment == null) {
                myFragment = new MyFragment();
                //加入事物
                beginTransaction.add(R.id.frame, myFragment);
            } else {
                //否则就显示
                beginTransaction.show(myFragment);
            }
            break;
    }
    //执行
    beginTransaction.commit();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值