我正在使用来自@ModelView库的Epoxy注释来创建CustomView。
我引用了另一个例子,但是下面的错误不断出现。
android.view.InflateException: Binary XML file line #2 in com.example.testepoxy:layout/item_custom_view: Binary XML file line #2 in com.example.testepoxy:layout/my_view: Error inflating class com.example.testepoxy.ItemCustomViewCaused by: java.lang.NullPointerException: findViewById(R.id.title) must not be null
at com.example.testepoxy.ItemCustomView.<init>(ItemCustomView.kt:21)
at com.example.testepoxy.ItemCustomView.<init>(ItemCustomView.kt:17)
at com.example.testepoxy.ItemCustomView.<init>(Unknown Source:11)它不是在使用默认布局时自动膨胀吗?我哪里出错了?
item_custom_view
<?xml version="1.0" encoding="utf-8"?>
<com.example.testepoxy.ItemCustomView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff0000">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ewq"/>
</com.example.testepoxy.ItemCustomView>模型
@ModelView(defaultLayout = R.layout.item_custom_view)
class ItemCustomView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
val textView: TextView = findViewById(R.id.title)
@TextProp
fun setText(title: CharSequence) {
textView.text = title
}
}控制器
class ItemCustomViewController : TypedEpoxyController<List<String>>() {
private val TAG = this::class.java.simpleName
override fun buildModels(data: List<String>?) {
data?.forEachIndexed { index, s ->
ItemCustomViewModel_()
.id(index)
.text(s)
.addTo(this)
}
}
}发布于 2022-07-05 12:22:44
使用lazy可以解决您的问题。
val textView: TextView by lazy{
findViewById(R.id.title)
}发布于 2022-10-16 13:26:18
您可以这样做来利用ViewBinding:
R.layout.item_custom_view:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</merge>@ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT)
class ItemCustomView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val binding = ItemCustomViewBinding.inflate(LayoutInflater.from(context), this)
// if you need to expose your child view
val textView: TextView get()= binding.title
@TextProp
fun setText(title: CharSequence) {
// or
// binding.title.text = title
textView.text = title
}}https://stackoverflow.com/questions/72866433
复制相似问题