美文网首页
Android ViewBinding封装(Java)

Android ViewBinding封装(Java)

作者: 听民谣的Superman | 来源:发表于2020-05-23 11:03 被阅读0次
    abstract class BaseActivity <T extends ViewBinding> extends AppCompatActivity {
    
        public T binding;
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //返回当前类的父类的Type,也就是BaseActivity
            Type type = this.getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                //如果支持泛型
                try {
                    //获得泛型中的实际类型,可能会存在多个泛型,[0]也就是获得T的type
                    Class<T> clazz = (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];
                    //反射inflate
                    Method method = clazz.getMethod("inflate", LayoutInflater.class);
                    //方法调用,获得ViewBinding实例
                    binding = (T) method.invoke(null, getLayoutInflater());
                }  catch (Exception e) {
                    e.printStackTrace();
                }
                setContentView(binding.getRoot());
            }
            init();
        }
        abstract void init();
    }
    
    
    public class MainActivity extends BaseActivity<ActivityMainBinding> {
        @Override
        void init() {
            binding.tvHello.setText("binding get");
        }
    }
    
    
    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 {
                    Class<T> clazz = (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];
                    Method method = clazz.getMethod("inflate", LayoutInflater.class, ViewGroup.class, Boolean.class);
                    binding = (T) method.invoke(null, 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();
        }
    
        abstract void init();
    
    }
    
    

    相关文章

      网友评论

          本文标题:Android ViewBinding封装(Java)

          本文链接:https://www.haomeiwen.com/subject/vvskahtx.html