package com.duqing.missions.base; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.viewbinding.ViewBinding; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; /** * Created by Administrator on 2021/10/28 0028. */ public abstract class BaseFragment extends Fragment { protected A activity; protected B binding; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { // get genericity "B" Class entityClass = (Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]; try { Method method = entityClass.getMethod("inflate", LayoutInflater.class,ViewGroup.class,boolean.class);//get method from name "inflate"; binding = (B) method.invoke(entityClass,inflater,container,false);//execute method to create a objct of viewbind; } catch (Exception e) { e.printStackTrace(); } return binding.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); activity = (A) getActivity(); initViews(); } public abstract void initViews(); @Override public void onDestroyView() { super.onDestroyView(); binding = null; } }