Programmers are lazy creatures. We always think of easy ways to simplify our code. We even have artificial intelligence to write code for us

Next, I write about the programmer’s struggle with findviewbyId

1. The most primitive method

ImageView tabIcon;
tabIcon = (ImageView) view.findViewById(R.id.tab_item_icon);
Copy the code

If you write a method like this, does it feel ok, but if it is dozens of ids?

The programmer says, I’m broken, I don’t do that, I’m lazy

2. Use a ButterKnife

@BindView(R.id.debug_tv_netWorkInfo)
TextView mDebugTvNetWorkInfo;
Copy the code

FindviewById, findviewById, findviewById, findviewById, findviewById, findviewById

3, ViewBinding

binding = FragmentOrderBinding.bind(inflate);  
binding.tvName.text = "Simple"
Copy the code

Binding.tvname (binding.tvname, binding.tvname, binding.tvname

4, kotlin – android – extensions

importkotlinx.android.synthetic.main.layout_agreement.view.* tvAgreement? .text = LoginConstants.PRIVACY_TITLECopy the code

In this way, we don’t even need a binding, just use the corresponding ID

5. There are other ways to encapsulate yourself

Use Kotlin’s Ext wrapper

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

private val mBtnGetPf: Button by id(R.id.btn_pf_get)
Copy the code