这是我能想到的最简单的 kotlin 答案。它是一个自定义视图,只包装了一个 TextView 并提供了update(s:String)
更新文本的功能。
<!-- view_stub.xml -->
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</layout>
// StubView.kt
class StubView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context,attrs,defStyleAttr) {
val binding = ViewStubBinding.inflate(context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater)
.also { addView(it.root) }
fun update(updatedText: String) {
binding.myTextView.text = updatedText
}
}
我喜欢这个答案的两点是:
binding
是 aval
而不是 a var
。我尽量限制var
s 的数量。
- 这
addView
与val binding
使用also {}
范围函数而不是init {}
子句密切相关,使得View
感觉的实例化更具声明性。
有人可能会争辩说,这addView()
确实是一种副作用,应该在该部分中,以便与valinit {}
的声明分开。binding
我会反对——声明 aval
然后将其提供给需要它的代码段对我来说并不像副作用。