- Kotlin優(yōu)化了復雜界面大段大段的findViewById代碼吧秕,取而代之的是導包形式:
import kotlinx.android.synthetic.main.布局文件.*
之后直接根據(jù)控件的ID獲取控件對象隧期,如:
<Button
android:id="@+id/QRCode"
android:text="QRCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
直接調(diào)用链峭,不需要額外的代碼
QRCode.setOnClickListener(this)
大概是在Kotlin1.3.2版本以前袁串,當一個xml文件中include其他xml文件時簿姨,通過將子xml文件import進去堕扶,也可以直接根據(jù)id獲得控件對象爱沟。當我更新到1.3.2版本后徊件,根據(jù)id得到的控件并不是界面顯示的那個對象奸攻,使用時就會報KotlinNullPointException。
通過給include的xml添加id
<include
android:id="@+id/mLayout_home_to_audit_info"
layout="@layout/item_home_today_info" />
在父view中findViewById獲取子view對象(fragment中)
private fun initView() {
mLayout_home_to_audit_info = root!!.findViewById(R.id.mLayout_home_to_audit_info)
}
之后使用中才不會空指針異常
Layout_home_to_audit_info!!.visibility = View.GONE `