在android中替代和快速替换findViewById
我怎样才能避免在我的应用程序中使用findViewById。 布局是非常复杂的,findViewById遍历它的树来查找需要时间的视图,并且它被使用了好几次。
首先,您必须编辑您的应用程序的build.gradle文件,并将以下内容添加到android块中:
android { … dataBinding.enabled = true }
另一个选择是Kotlin的Android扩展。
// Using R.layout.activity_main from the main source set import kotlinx.android.synthetic.main.activity_main.* class MyActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Instead of findView(R.id.textView) as TextView textView.setText("Hello, world!") } }
你有几个选择,主要有两个:
Android数据绑定: https : //developer.android.com/topic/libraries/data-binding/index.html
要么
Butterknife: http ://jakewharton.github.io/butterknife/
就我个人而言,我是Butterknife的粉丝,在可能的地方使用它,值得注意的是,这只是让你的代码更好看。 我发现Android的数据绑定比Butter Knifes复杂得多(这是更多的人的意见,虽然…)
据我所知,你可以使用视图绑定或findViewByID。 这里清楚的是他们做同样的事情。 数据/视图绑定将只在编译时写入findViewByID。
视图绑定只是让你的代码更容易阅读。 我没有意识到任何更改的android以外,很快你将不再需要投你的findViewByIDs。