【安卓】android Fragment View的缓存以实现重复利用

本文介绍了一种在Android应用中使用Fragment时实现视图缓存的方法,通过重写onCreateView方法并缓存Fragment的根视图,避免了重复加载布局资源,提高了用户体验。

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

public class HotFragment extends Fragment {

    private View mRootView;//缓存fragment View
    private RecyclerView mRecycleView;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if(mRootView==null){
           mRootView=inflater.inflate(R.layout.fragment_listview,null);
        }
        //缓存的rootView需要判断是否已经被加过parent, 如果有parent则parent删除,防止发生这个rootview已经有parent的错误。
        ViewGroup mViewGroup = (ViewGroup)mRootView.getParent();
        if(mViewGroup!=null){
            mViewGroup.removeView(mRootView);
        }
        return mRootView;
    }
}

接下来说明下

  以上代码是为了实现在多个fragement 实现View的缓存





欢迎关注我的博客   和 github  https://github.com/xingwen93

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值