Administrator
2021-10-27 2c2b6a3821d1e4ffbb2a0511d45943aae1992e55
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
package com.duqing.missions.base;
 
import android.os.Bundle;
import android.view.LayoutInflater;
 
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;
 
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
 
/**
 * Created by Administrator on 2021/10/27 0027.
 */
public abstract class BaseActivity<B extends ViewBinding> extends AppCompatActivity {
 
    protected  B binding;
 
 
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // get genericity "B"
        Class<B> entityClass = (Class<B>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        try {
            Method method = entityClass.getMethod("inflate", LayoutInflater.class);//get method from name "inflate";
            binding = (B) method.invoke(entityClass,getLayoutInflater());//execute method to create a objct of viewbind;
        } catch (Exception e) {
            e.printStackTrace();
        }
        setContentView(binding.getRoot());
    }
}