package union.com.viewgroup.ui.frgment;
import android.content.Context;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import union.com.viewgroup.R;
/*
* @Auther xiaobo
* @Date 2019/8/27 18:42
* @Version 1.0
* @Desc Fragment viewPager 中懒加载机制
*/
public class BaseLazyBaseFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private boolean isViewCreated; // 界面是否已创建完成
private boolean isVisibleToUser; // 是否对用户可见
private boolean isDataLoaded; // 数据是否已请求
public static BaseLazyBaseFragment newInstance(int position) {
BaseLazyBaseFragment fragment = new BaseLazyBaseFragment();
Bundle bundle = new Bundle();
bundle.putInt("params1",position);
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}
@Override
public void onResume() {
super.onResume();
int arms = getArguments().getInt("params1");
Log.i("grage","onResume----arms="+arms);
isViewCreated = true;
loadData();
}
/**
* 数据处理
*/
private void loadData() {
if( isViewCreated && isVisibleToUser && isParentVisible() && !isDataLoaded){
isDataLoaded = true;
int arms = getArguments().getInt("params1");
Log.i("grage","setUserVisibleHint----arms="+arms);
dispatchParentVisibleState();
}
}
/**
* ViewPager场景下,当前fragment可见时,如果其子fragment也可见,则让子fragment请求数据
*/
private void dispatchParentVisibleState() {
FragmentManager fragmentManager = getChildFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if (fragments.isEmpty()) {
return;
}
for (Fragment child : fragments) {
if (child instanceof Fragment && ((BaseLazyBaseFragment) child).isVisibleToUser) {
((BaseLazyBaseFragment) child).loadData();
}
}
}
/**
* viewPager 切换时会调用该方法
* @param isVisibleToUser 是否对用户可见
*/
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
int arms = getArguments().getInt("params1");
Log.i("grage","setUserVisibleHint="+arms);
super.setUserVisibleHint(isVisibleToUser);
this.isVisibleToUser = isVisibleToUser;
loadData();
}
/**
* ViewPager场景下,判断父fragment是否可见
*/
private boolean isParentVisible() {
Fragment fragment = getParentFragment();
return fragment == null || (fragment instanceof BaseLazyBaseFragment && ((BaseLazyBaseFragment) fragment).isVisibleToUser);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void onDestroy() {
super.onDestroy();
}
}