我想使用具有自定义视图的ViewBinding,例如:
MainActivity <=> layout_main.xml
MyCustomView <=> layout_my_custom_view.xmllayout_main.xml
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.myapplication.MyCustomView
android:id="@+id/custom_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>layout_my_custom_view.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/line1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Line1" />
<View
android:id="@+id/divider"
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#2389bb" />
<TextView
android:id="@+id/line2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Line2" />
</LinearLayout>MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var binding: LayoutMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = LayoutMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.customView.line1.text = "Hello"
binding.customView.line2.text = "World"
}
}在我的MainActivity中,我可以使用绑定来查找MyCustomView,但不能在MyCustomView中进一步找到@id/line1和@id/line2。在这种情况下,是否可以只使用ViewBinding,还是必须使用findViewById或Kotlin合成?
提前谢谢。
发布于 2020-02-27 03:15:15
ViewDataBinding.inflate不会在自定义视图中生成子视图访问器。
因此,您不能只通过使用line1(TextView)来触摸ViewDataBinding。
如果不想使用findViewById或kotlin synthetic,MyCustomView也需要应用ViewDataBinding。试一试如下。
CustomView
class MyCustomView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private val binding =
CustomLayoutBinding.inflate(LayoutInflater.from(context), this, true)
val line1
get() = binding.line1
val line2
get() = binding.line2
}MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(LayoutInflater.from(this))
setContentView(binding.root)
with(binding.customView) {
line1.text = "Hello"
line2.text = "World"
}
}发布于 2021-07-19 15:40:17
另一种方法是返回CustomView绑定object。
class CustomView constructor(context: Context, attrs: AttributeSet?) :
ConstraintLayout(context, attrs){
private val _binding: CustomViewBinding = CustomViewBinding.inflate(
LayoutInflater.from(context), this, true)
val binding get() = _binding
}然后在你的Activity或Fragment里
binding.customView.binding.line1?.text = "Hello"
binding.customView.binding.line2?.text = "World"发布于 2020-02-27 02:45:55
我相信你可以在你的自定义视图中设置设置器。因为ViewBinding为主布局生成绑定类,所以它应该返回CustomView类。因此,您可以使用您刚刚编写的设置器来更改文本。
https://stackoverflow.com/questions/60425304
复制相似问题