Administrator
2021-10-28 9fbcdc146440b49ef80714c1336c226e00727da8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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<A extends BaseActivity,B extends ViewBinding> extends Fragment {
 
    protected  A activity;
    protected  B binding;
 
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        // get genericity "B"
        Class<B> entityClass = (Class<B>) ((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;
    }
 
}