Der*_*rek 6 android android-layout kotlin
我有一个自定义视图:
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"
}
}
Run Code Online (Sandbox Code Playgroud)
我的布局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>
Run Code Online (Sandbox Code Playgroud)
但是当我在另一个页面调用它时,应用程序崩溃说
引起:java.lang.IllegalStateException: findViewById(R.id.txtTestName) 在 com.helcim.helcimcommercemobile.customviews.CustomerView.(CustomerView.kt:19) 处不能为空
这是我尝试分配的时候 txtName
当我在布局视图中拥有它时,我真的不明白它是如何为空的。它的名字相同。
我是否错误地创建了自定义视图?
您必须将父布局作为参数添加到 'inflate' 方法。
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, this)
txtName = findViewById(R.id.txtTestName)
txtAge = findViewById(R.id.txtTestAge)
txtName.text = "Derek"
txtAge.text = "23"
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2978 次 |
| 最近记录: |