干掉findViewById,3种方法总有一款适合你

相信大家用AS写页面的时候,最烦的就是findViewById,尤其是复杂布局,那感觉太酸爽😂,下面的3中方法我在项目中都在使用,目前感觉良好😄,废话不多说,文章正式开始~

方案一:使用Android Studio 3.6新特性(附demo)

3.6版本的AS可以进行View Binding,View Binding后可以通过布局的xml文件生成绑定类来实现与view交互,先用起来:
1.AS在3.6.0及以上
在这里插入图片描述
2.build gradle在3.6.0及以上

classpath 'com.android.tools.build:gradle:3.6.0'

3.在每一个使用View Binding的module中配置

android {
	...//注意配置在android下
    viewBinding {
        enabled = true;
    }
}

4.比如布局文件的名字是activity_test_binding.xml,在Activity中使用的时候,先获取xml文件生成的绑定类,这里我的布局文件是activity_test_binding.xml,所以用

ActivityTestBindingBinding mBinding = ActivityTestBindingBinding.inflate(getLayoutInflater());
setContentView(mBinding.getRoot());

此时可以用mBinding 来获取布局中所有含有id视图的直接引用,可以直接通过mBinding.View的ID 来得到View对象,见下图
在这里插入图片描述
布局activity_test_binding.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.activity.TestBindingActivity">
    <Button
        android:text="测试view binding"
        android:id="@+id/btn_test_view_binding"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_width="match_parent"
        android:layout_height="50dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

在adapter和Fragment中使用时可以调用
布局名字Binding.bind(View)方法来获取绑定类。就不过多介绍了
想来个demo运行一下?点我!!!

方案二:使用Kotlin为Android提供的扩展插件kotlin-android-extensions

1.在module的build.gradle下配置插件

apply plugin: 'kotlin-android-extensions'
...
android{
...
	//ViewHolder中使用Extansions
    androidExtensions {
        experimental = true
    }
}

2.在Activity中导入
kotlinx.android.synthetic.main.布局名称.*
代码如下

import kotlinx.android.synthetic.main.activity_kotlin_test.*

class KotlinTestActivity:AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin_test)
        btn_kt_test.text = "button";
    }

}

方案三:使用butterknife

butterknife的相关介绍和使用方法可以点击链接进行浏览,我想说的是,我目前的项目是一个组件化的项目,使用了ARouter
框架,如果使用butterknife,会有一些问题,处于方便考虑,我组件话的项目中没采用这一方案。
如果还是想使用的话,推荐看一下下面这个文章的第七部分
Android butterknife在library组件化模块中的使用问题

总结

1.如果项目中没有使用Kotlin和ARouter组件话方案,推荐使用Android Studio 3.6新特性
2.如果项目是一个Kotlin项目或者有Kotlin代码module,可以在java的module中使用Android Studio 3.6新特性,Kotlin使用扩展插件kotlin-android-extensions
3.如果项目是使用ARouter组件化方案的项目的话,不建议使用butterknife

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章