我的BaseFragment
public abstract class BaseFragment<T extends ViewBinding> extends Fragment {
public T binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Type type = this.getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
// 如果支持泛型
try {
// 获得泛型中的实际类型,可能获得多个,[0]就是获得T的type
Class<T> tClass = (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];
// 通过反射获取inflate
Method method = tClass.getMethod("inflate", LayoutInflater.class, ViewGroup.class, Boolean.class);
// 获得viewBinding实例
binding = (T) method.invoke(null,getLayoutInflater(),container, false);
} catch (Exception e) {
e.printStackTrace();
}
}
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
protected abstract void init();
}
我的适配器类
public class ChartVPAdapter extends FragmentStateAdapter {
private List<Fragment> fragments;
public void setFragments(List<Fragment> f) {
fragments.clear();
fragments.addAll(f);
notifyDataSetChanged();
}
public ChartVPAdapter(@NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
fragments = new ArrayList<>();
}
@NonNull
@Override
public Fragment createFragment(int position) {
return fragments.get(position);
}
@Override
public int getItemCount() {
return fragments.size();
}
}
只要一运行就会报
Attempt to invoke interface method 'android.view.View androidx.viewbinding.ViewBinding.getRoot()' on a null object reference
求解