关于FindViewById的那些小事

程序员都是偷懒的生物,我们总想着可以省事的方法可以简化自己的代码,甚至有人工智能帮我们写代码

接下来,我写下程序员与findviewbyId的抗争

1,最原始的方法

ImageView tabIcon;
tabIcon = (ImageView) view.findViewById(R.id.tab_item_icon);
复制代码

如果写一个这样的方法,是不是感觉还行,哪如果是几十个id呢?

程序员表示,我崩溃了,这样的事,我不干,我要偷懒

2,使用ButterKnife

@BindView(R.id.debug_tv_netWorkInfo)
TextView mDebugTvNetWorkInfo;
复制代码

这样写是不是比findviewById方便很多啊,但是还是很麻烦啊,还要写那么多,我不服,我还要偷懒

3,ViewBinding

binding = FragmentOrderBinding.bind(inflate);  
binding.tvName.text = "简单"
复制代码

这样写,就初始化引入下,其他时候直接用binding.tvName 使用,更简便了

4,kotlin-android-extensions

import kotlinx.android.synthetic.main.layout_agreement.view.*
tvAgreement?.text = LoginConstants.PRIVACY_TITLE
复制代码

这样写,我们甚至都不要binding,直接使用对应的id

5,还有其他的一些自己封装的方法

使用kotlin的ext封装

fun <T : View> Activity.id(id: Int) = lazy {
    findViewById<T>(id)
}

private val mBtnGetPf: Button by id(R.id.btn_pf_get)
复制代码

猜你喜欢

转载自juejin.im/post/7039535742875336734