【发布时间】:2018-06-27 16:56:36
【问题描述】:
我有一个自定义视图:
class CustomerView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {
private var txtName: TextView
private var txtAge: TextView
init {
View.inflate(context, R.layout.view_customer, null)
txtName = findViewById(R.id.txtTestName)
txtAge = findViewById(R.id.txtTestAge)
txtName.text = "Person"
txtAge.text = "61"
}
}
我的布局view_customer 如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/txtTestName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name" />
<TextView
android:id="@+id/txtTestAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="age" />
</LinearLayout>
但是当我在我的其他页面中调用它时,应用程序崩溃说
引起:java.lang.IllegalStateException: findViewById(R.id.txtTestName) 不能为空 在 com.helcim.helcimcommercemobile.customviews.CustomerView.(CustomerView.kt:19)
这是我尝试分配txtName的时候
当我将它放在布局视图中时,我真的不明白它是如何为 null 的。并且命名相同。
我是否错误地创建了自定义视图?
【问题讨论】:
-
使用从
View.inflate返回的视图|View x = View.inflate()|x.findViewById()
标签: android android-layout kotlin