ViewPager+Fragment 懒加载

本文介绍了一个自定义Fragment基类的设计方案,通过维护几个关键布尔变量的状态来实现Fragment可见性的智能管理,有效避免了ViewPager缓存机制导致的问题,并提供了示例代码。

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

1、首先定义一个基类BaseFragment 

2、

//定义一个View加载布局

private View view;

// 定义 rootView是否初始化标志,防止回调函数在rootView为空时触发

private boolean hasCreateView;

// 判断当前Fragment是否可见标志,防止ViewPager缓存机制而导致回调函数的触发

private boolean isFragmentVisible;

3、

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_base, container, false);
    return view;
}
public void setUserVisibleHint(boolean isVisibleToUser){
        super.setUserVisibleHint(isVisibleToUser);

        if(view == null){
            return;
        }
        
        hasCreateView = true;
        
        if(isVisibleToUser){
            onFragmentVisibleChange(true);
            isFragmentVisible = true;
            return;
        }
        
        if(isFragmentVisible){
            onFragmentVisibleChange(false);
            isFragmentVisible = false;
        }

}

//初始化判断的boolean值 在onCreate里调用

private void initVisible(){

    hasCreateView = false;

    isFragmentVisible = false;

/**

当前Fragment可见状态时会调用次方法

如果当前Fragment是第一次加载,等待onCreateView后才调用该方法,其他情况调用时机跟setUserVisibleHint(boolean isVisibleToUser) 一样

在该方法中可以调用一些网络请求,也可以是控件的操作,因为配合fragment复用view 机制,所以不用担心会报空指针异常

**/

protected void onFragmentChange(boolean isVisible){

}

//在onViewCreated进行判断

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if (!hasCreateView && getUserVisibleHint()) {
        onFragmentVisibleChange(true);
        isFragmentVisible = true;
    }
}

在Fragment里面调用

 

@Override
protected void onFragmentVisibleChange(boolean isVisible) {
    super.onFragmentVisibleChange(isVisible);
    if (isVisible) {
     //进行操作
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值