安卓开发,ViewBinding的简单使用和封装。

介绍

ViewBinding是什么?ViewBinding是一项功能,可以让你轻松地编写与视图的交互代码,它可以自动为每个xml布局文件生成一个绑定类,包含了所有ID的视图的直接引用。非常方便。

开启ViewBinding

启用它非常简单,只需要在app模块级的build.gradle中加入以下代码。

//在app:级的build.gradle里的Android{}闭包中加入以下代码,然后右上角Sync now
//启用DataBinding
android {
        ...
        //启用viewBinding
        viewBinding {
            enabled = true
        }
    }
    

兄弟DataBinding

它有一个非常相近的兄弟,叫做DataBinding。这两者最显著的区别就是,DataBinding不会自动生成绑定文件,而是要手动加。DataBinding支持数据绑定与页面控件的双向绑定,能够实现数据与页面的联动,而不需要写太多代码。

我曾今也用过dataBinding也写过样例《安卓开发,DataBinding简单使用和封装》,当时对它绑定实体类做单向绑定或者双向绑定的功能一知半解,后来了解之后发现,这个功能其实并不适合复杂的业务开发,通常维持页面数据需要很多实体类,但是 xml未必能够一一对应实体类,这样复用页面也有难度,同时绑定要在xml设置控件与实体的联系@{viewmodel.userName}。一旦业务复杂会导致代码阅读不直观,不好分析等问题,所以在了解之后,我放弃了databinding的继续研究,转而用起了viewBinding。

封装ViewBinding

页面中

viewBinding的页面什么都不用做,是不是很方便?

Activity中

package com.bbyyxx2.myqrproject.ui.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

import java.lang.reflect.ParameterizedType;

public abstract class BaseActivity<VB extends ViewBinding, VM extends ViewModel> extends AppCompatActivity {

    public VB binding;
    public Context context;
    public Activity activity;
    public VM viewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //ParameterizedType是获取传递过来的泛型类
        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
        viewModel = new ViewModelProvider(this).get( (Class<VM>) superClass.getActualTypeArguments()[1]);
        binding = inflateViewBinding(getLayoutInflater());
        setContentView(binding.getRoot());
        context = this;
        activity = this;
        initView();
        initListener();
    }

    protected abstract VB inflateViewBinding(LayoutInflater layoutInflater);

    public void initView() {

    }

    public void initListener(){

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //释放持有,防止泄露
        binding = null;
    }
}

在fragment中

package com.bbyyxx2.myqrproject.ui.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

import java.lang.reflect.ParameterizedType;

public abstract class BaseFragment<VB extends ViewBinding, VM extends ViewModel> extends Fragment {

    public VB binding;
    public Context context;
    public Activity activity;
    public VM viewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
        viewModel = new ViewModelProvider(this).get( (Class<VM>) superClass.getActualTypeArguments()[1]);
        binding = inflateViewBinding(inflater, container);
        context = requireContext();
        activity = requireActivity();
        initView();
        initListener();
        return binding.getRoot();
    }

    /**
     * 一定要复写的,不然会报错,用于viewBinding的代码和页面关联。
     * 方法内只需要一行eg:return FragmentScanBinding.inflate(inflater, container, false);
     * @param inflater
     * @param container
     * @return
     */
    protected abstract VB inflateViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container);
    public void initView(){

    }

    public void initListener() {

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //释放持有,防止泄露
        binding = null;
    }
}

其实代码基本逻辑是一样的不论是在act中还是ftagment中。通过泛型来实现书写更少的代码。不过ViewBinding的初始化必须由对应页面的绑定类亲自inflate,目前我采用的是抽象方法到子类代码里。
使用的时候就继承写一行就好。

public class TestFragment extends BaseFragment<FragmentTestBinding, TestViewModel> {

    @Override
    protected FragmentTestBinding inflateViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        return FragmentTestBinding.inflate(inflater, container, false);
    }
    
}

使用ViewBinding

假设xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.setting.SettingFragment">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

需要注意的是,ViewBinding中的id映射成字段后,是根据下划线转换为驼峰.eg: android:id=“@+id/text_title”,使用的时候则是binding.textTitle;

public class TestFragment extends BaseFragment<FragmentTestBinding, TestViewModel> {

	void Test(){
		binding.tv.setTextView("Hello world");
	}
    
}

优化

也可以想办法让子类一行不写的,那就是反射。从上述代码中看到,我们其实可以取到泛型的对应class,那也就是说,通过反射我们可以直接调用对应绑定类的对应方法
(ps:注意如果项目开启了混淆,直接使用反射,在release包中会报错,因为inflate方法在混淆中会被混淆,网上的keep进行尝试后无果,后续实践后贴出解决方案已解决)

//以baseFragment举例
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
        viewModel = new ViewModelProvider(this).get( (Class<VM>) superClass.getActualTypeArguments()[1]);

        try {
            Class<VB> cls = (Class<VB>) superClass.getActualTypeArguments()[0];
            Method method = cls.getMethod("inflate", LayoutInflater.class, ViewGroup.class, Boolean.TYPE);
            method.setAccessible(true);
            binding = (VB) method.invoke(null, inflater,container, Boolean.FALSE);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

//        binding = inflateViewBinding(inflater, container);
        context = requireContext();
        activity = requireActivity();
        initView();
        initListener();
        return binding.getRoot();
    }
	//以baseActivity举例
	@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //ParameterizedType是获取传递过来的泛型类
        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
        viewModel = new ViewModelProvider(this).get( (Class<VM>) superClass.getActualTypeArguments()[1]);

        try {
            Class<VB> cls = (Class<VB>) superClass.getActualTypeArguments()[0];
            Method method = cls.getMethod("inflate", LayoutInflater.class);
            method.setAccessible(true);
            binding = (VB) method.invoke(null, getLayoutInflater());
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        setContentView(binding.getRoot());
        context = this;
        activity = this;
        initView();
        initListener();
    }

使用反射调用inflate方法实现子类不需要干任何事情,也不存在忘写而异常闪退。

优化优化

//开启混淆
//app级的build.gradle(:app)中的Android闭包{}
buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        debug {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
//项目中对应模块中的proguard-rules.pro中加入,这样上述优化中的反射,在混淆中就不会出问题
-keep class * extends androidx.viewbinding.ViewBinding {*;}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值