【android】如何使用ViewBinding 替换findViewById 和 ButterKnife ?

顾名思义

ViewBinding 是google推出Jetpack库的一个组件,主要用于视图绑定,替代 findViewById操作.Viewbinding会根据xml文件生成一个对应的绑定类, 比如我们xml文件是: activity_login_layout.xml 生成的绑定类就是ActivityLoginLayoutBinding 这么一个类.在使用的时候直接通过生成的绑定类调用我们xml中的视图组件, 不用findViewById,也不用声明组件. 接下来看下我们集成和项目就能很快的理解.

集成

首先在我们工程build.gradld中引入viewBind

    //引入ViewBinding
    viewBinding {
        viewBinding = true
    }

然后我们就可以在代码中使用ViewBinding了

代码

创建了一个登录页面, activity_login_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    tools:viewBindingIgnore="false"
    android:padding="16dp">

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/tv_login_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="登录"
        android:textColor="@color/design_default_color_primary_variant"
        android:textSize="19sp" />

    <androidx.appcompat.widget.AppCompatEditText
        android:id="@+id/et_login_account"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="10dp"
        android:hint="用户名"
        android:paddingStart="10dp"
        android:paddingEnd="10dp" />

    <androidx.appcompat.widget.AppCompatEditText
        android:id="@+id/et_login_pwd"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="10dp"
        android:hint="密码"
        android:paddingStart="10dp"
        android:paddingEnd="10dp" />

    <Button
        android:id="@+id/btn_login"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="20dp"
        android:background="@color/design_default_color_secondary"
        android:text="登录"
        android:textSize="20dp" />

    <TextView
        android:id="@+id/tv_find_pwd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        android:text="找回密码"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="16sp" />
</LinearLayout>

image

接下来我们看下用findViewById方式获取id并且设置点击事件等


class LoginActivity2 : AppCompatActivity(R.layout.activity_login_layout) {
   //先声明控件
    lateinit var etAccount: EditText
    lateinit var etPwd: EditText
    lateinit var btnLogin: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
    }

    private fun initView() {
    //挨个findViewById 初始化控件
        etAccount = findViewById(R.id.et_login_account)
        etPwd = findViewById(R.id.et_login_pwd)
        btnLogin = findViewById(R.id.btn_login)
        btnLogin.setOnClickListener {
            var accountInfo = etAccount.text
            var accountPwd = etPwd.text
            if (!TextUtils.isEmpty(accountInfo)) {
                if (!TextUtils.isEmpty(accountPwd)) {
                    Log.e("ping", "执行登录操作:用户名:$accountInfo 密码: $accountPwd")
                } else {
                    Log.e("ping", "请输入密码")
                }
            } else {
                Log.e("ping", "请输入用户名")
            }
        }
    }
}

在看下用ViewBinding的代码


class LoginActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLoginLayoutBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginLayoutBinding.inflate(layoutInflater)
        val view = binding.root;
        setContentView(view)
        initView()
    }

    private fun initView() {
        binding.btnLogin.setOnClickListener {
            var accountInfo = binding.etLoginAccount.text
            var accountPwd = binding.etLoginPwd.text
            if (!TextUtils.isEmpty(accountInfo)) {
                if (!TextUtils.isEmpty(accountPwd)) {
                    Log.e("ping", "执行登录操作:用户名:$accountInfo 密码: $accountPwd")
                } else {
                    Log.e("ping", "请输入密码")
                }
            } else {
                Log.e("ping", "请输入用户名")
            }
        }
    }
}

是不是很直观, 不需要声明控件,也不需要findViewById 直接用 ActivityLoginLayoutBinding绑定类 . 操作就可以, 是不是很Nice. 这个时候你又说了,这样我不知道那个是那个控件怎么办? 我们来看下ActivityLoginLayoutBinding类的代码:


public final class ActivityLoginLayoutBinding implements ViewBinding {
    @NonNull
    private final LinearLayout rootView;
    @NonNull   //android:id="@+id/btn_login"    
    public final Button btnLogin;  //根据我们在xml中定义的id 驼峰命名发声明控件    
    @NonNull  //android:id="@+id/et_login_account"
    public final AppCompatEditText etLoginAccount;
    @NonNull  //android:id="@+id/et_login_pwd"
    public final AppCompatEditText etLoginPwd;
    @NonNull  // android:id="@+id/tv_find_pwd"
    public final TextView tvFindPwd;
    @NonNull
    public final AppCompatTextView tvLoginTitle;

    private ActivityLoginLayoutBinding(@NonNull LinearLayout rootView, @NonNull Button btnLogin, @NonNull AppCompatEditText etLoginAccount, @NonNull AppCompatEditText etLoginPwd, @NonNull TextView tvFindPwd, @NonNull AppCompatTextView tvLoginTitle) {
        this.rootView = rootView;
        this.btnLogin = btnLogin;
        this.etLoginAccount = etLoginAccount;
        this.etLoginPwd = etLoginPwd;
        this.tvFindPwd = tvFindPwd;
        this.tvLoginTitle = tvLoginTitle;
    }

    @NonNull
    public LinearLayout getRoot() {
        return this.rootView;
    }

    @NonNull
    public static ActivityLoginLayoutBinding inflate(@NonNull LayoutInflater inflater) {
        return inflate(inflater, (ViewGroup)null, false);
    }

    @NonNull
    public static ActivityLoginLayoutBinding inflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent, boolean attachToParent) {
        View root = inflater.inflate(2131427356, parent, false);
        if (attachToParent) {
            parent.addView(root);
        }

        return bind(root);
    }

    @NonNull
    public static ActivityLoginLayoutBinding bind(@NonNull View rootView) {
        int id = 2131230807;
        Button btnLogin = (Button)ViewBindings.findChildViewById(rootView, id);
        if (btnLogin != null) {
            id = 2131230876;
            AppCompatEditText etLoginAccount = (AppCompatEditText)ViewBindings.findChildViewById(rootView, id);
            if (etLoginAccount != null) {
                id = 2131230877;
                AppCompatEditText etLoginPwd = (AppCompatEditText)ViewBindings.findChildViewById(rootView, id);
                if (etLoginPwd != null) {
                    id = 2131231121;
                    TextView tvFindPwd = (TextView)ViewBindings.findChildViewById(rootView, id);
                    if (tvFindPwd != null) {
                        id = 2131231122;
                        AppCompatTextView tvLoginTitle = (AppCompatTextView)ViewBindings.findChildViewById(rootView, id);
                        if (tvLoginTitle != null) {
                            return new ActivityLoginLayoutBinding((LinearLayout)rootView, btnLogin, etLoginAccount, etLoginPwd, tvFindPwd, tvLoginTitle);
                        }
                    }
                }
            }
        }

        String missingId = rootView.getResources().getResourceName(id);
        throw new NullPointerException("Missing required view with ID: ".concat(missingId));
    }
}

其实ViewBinding自动为我们声明控件,并且执行fingViewById,我们只需要在用的时候直接用 binding.btnLogin 等等

在Activity中如何视图绑定

Activity中使用视图绑定的话需要在 的 onCreate() 方法中执行以下步骤:

  • 调用生成的绑定类中包含的静态 inflate() 方法。此操作会创建该绑定类的实例以供 Activity 使用。
  • 通过调用 getRoot() 方法或使用 Kotlin 属性语法获取对根视图的引用。
  • 将根视图传递到 setContentView(),使其成为屏幕上的活动视图。

    private lateinit var binding: ActivityLoginLayoutBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginLayoutBinding.inflate(layoutInflater)
        val view = binding.root;
        setContentView(view)
    }

然后就可以使用视图上任何定义的View了,例如:


binding.btnLogin.setOnClickListener {
            var accountInfo = binding.etLoginAccount.text
            var accountPwd = binding.etLoginPwd.text
            if (!TextUtils.isEmpty(accountInfo)) {
                if (!TextUtils.isEmpty(accountPwd)) {
                    Log.e("ping", "执行登录操作:用户名:$accountInfo 密码: $accountPwd")
                } else {
                    Log.e("ping", "请输入密码")
                }
            } else {
                Log.e("ping", "请输入用户名")
            }
        }
    }

在 Fragment 中使用视图绑定

在Fragment使用视图绑定,首先需要在 onCreateView() 方法中执行以下步骤:

  • 调用生成的绑定类中包含的静态 inflate() 方法。此操作会创建该绑定类的实例以供 Fragment 使用。
  • 通过调用 getRoot() 方法或使用 Kotlin 属性语法获取对根视图的引用。
  • 从 onCreateView() 方法返回根视图,使其成为屏幕上的活动视图。

class LoginFragment : Fragment() {
    private lateinit var binding: ActivityLoginLayoutBinding 
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = ActivityLoginLayoutBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        null.also { it -> binding = it }
    }
}

然后就能愉快的使用了我们视图上定义的view啦

 binding.btnLogin.setOnClickListener {
            //执行登录操作
        }

总结

与findViewById相比,很明显的优点是,代码量减少,使用更加简单,减少了很多无用的操作. 还有就是

  • Null 安全:由于视图绑定会创建对视图的直接引用,因此不存在因视图 ID 无效而引发 Null 指针异常的风险。此外,如果视图仅出现在布局的某些配置中,则绑定类中包含其引用的字段会使用 @Nullable 标记。
  • 类型安全:每个绑定类中的字段均具有与它们在 XML 文件中引用的视图相匹配的类型。这意味着不存在发生类转换异常的风险。

优点

  • 更快的编译速度:视图绑定不需要处理注释,因此编译时间更短
  • 易于使用:视图绑定不需要特别标记的 XML 布局文件,因此在应用中采用速度更快。在模块中启用视图绑定后,它会自动应用于该模块的所有布局。

缺点

  • 视图绑定不支持布局变量或布局表达式,因此不能用于直接在 XML 布局文件中声明动态界面内容。
  • 视图绑定不支持双向数据绑定。

以上就是ViewBinding的全部内容啦, 如果觉得不错,不妨点个赞.谢谢.

作者:Android高级架构
链接:https://www.jianshu.com/p/1589d1d23ed2

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,306评论 4 370
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,657评论 2 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,928评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,688评论 0 220
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,105评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,024评论 1 225
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,159评论 2 318
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,937评论 0 212
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,689评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,851评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,325评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,651评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,364评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,192评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,985评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,154评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,955评论 2 279

推荐阅读更多精彩内容

  • 一、什么是ViewBinding View Binding是Android Studio 3.6推出的新特性,旨在...
    小O机阅读 16,936评论 0 17
  • 1、概述 使用ViewBinding后,系统会自动为每一个xml布局文件生成一个绑定类,通过这个绑定类的实例,可以...
    伤口不该结疤阅读 1,204评论 0 1
  • 表情是什么,我认为表情就是表现出来的情绪。表情可以传达很多信息。高兴了当然就笑了,难过就哭了。两者是相互影响密不可...
    Persistenc_6aea阅读 120,790评论 2 7
  • 16宿命:用概率思维提高你的胜算 以前的我是风险厌恶者,不喜欢去冒险,但是人生放弃了冒险,也就放弃了无数的可能。 ...
    yichen大刀阅读 5,990评论 0 4