ViewBinding基类封装的正确打开方式

我们在日常开发中,为了避免findViewById这种低效的代码编写,可以基于ViewBinding库封装基类。但是网上很多是不正确的,今天就贴出正确的打开方式。

引入ViewBinding:

implementation 'androidx.databinding:viewbinding:7.1.2'

配置ViewBinding(app的build.gradle)可用:

android {
    ···

    buildFeatures {
        viewBinding true
    }

}

BaseActivity基类:

public abstract class BaseActivity extends AppCompatActivity {

    public T binding;

    @Override
    @SuppressWarnings("unchecked")
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Type type = this.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            try {
                Class clazz = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
                Method method = clazz.getMethod("inflate", LayoutInflater.class);
                binding = (T) method.invoke(null, getLayoutInflater());
            } catch (Exception e) {
                e.printStackTrace();
            }
            assert binding != null;
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(binding.getRoot());
        }
        init();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {
        AutoSize.autoConvertDensityOfGlobal(this);
        return super.onCreateView(name, context, attrs);
    }

    public void launchFragment(Class fragmentClass, @IdRes int containerViewId) {
        this.launchFragment(fragmentClass, containerViewId, null);
    }

    public void launchFragment(Class fragmentClass, @IdRes int containerViewId, Bundle args) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragmentInstance = fragmentManager.findFragmentByTag(fragmentClass.getName());
        if (fragmentInstance != null) {
            fragmentTransaction.remove(fragmentInstance);
        }
        fragmentTransaction.add(containerViewId, fragmentClass, args, fragmentClass.getName());
        /* 入栈. */
        if (!DialogFragment.class.isAssignableFrom(fragmentClass)) {
            fragmentTransaction.addToBackStack(fragmentClass.getName());
        }
        fragmentTransaction.commit();
    }

    public int pt2px(float pt) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, pt, getResources().getDisplayMetrics());
    }

    protected abstract void init();

}

BaseFragment基类:

public abstract class BaseFragment extends Fragment {

    public T binding;

    @Nullable
    @Override
    @SuppressWarnings("unchecked")
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Type type = this.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            try {
                Class clazz = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
                Method method = clazz.getDeclaredMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
                binding = (T) method.invoke(null, inflater, container, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        assert binding != null;
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        /* 防止点击穿透. */
        view.setClickable(true);
        init();
    }

    public void launchFragment(Class fragmentClass, @IdRes int containerViewId) {
        this.launchFragment(fragmentClass, containerViewId, null);
    }

    public void launchFragment(Class fragmentClass, @IdRes int containerViewId, Bundle args) {
        FragmentManager fragmentManager = requireActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragmentInstance = fragmentManager.findFragmentByTag(fragmentClass.getName());
        if (fragmentInstance != null) {
            fragmentTransaction.remove(fragmentInstance);
        }
        fragmentTransaction.add(containerViewId, fragmentClass, args, fragmentClass.getName());
        /* 入栈. */
        if (!DialogFragment.class.isAssignableFrom(fragmentClass)) {
            fragmentTransaction.addToBackStack(fragmentClass.getName());
        }
        fragmentTransaction.commit();
    }

    public int pt2px(float pt) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, pt, getResources().getDisplayMetrics());
    }

    protected abstract void init();

}

特别注意不要写成这样!

Method method = clazz.getDeclaredMethod("inflate", LayoutInflater.class, ViewGroup.class, Boolean.class);

Boolean对于java来说并不是基本数据类型,对于Kotlin才是基本数据类型。

你可能感兴趣的:(jetpack,java)