首页 > 解决方案 > Android - 创建自定义 xml 属性,如 onClick?

问题描述

我正在尝试创建一个自定义视图,其中包含两个按钮,分别是 OK 和 Cancel。我的视图模型中有两种方法说fun onOkClicked(view View)fun onCancelClicked(view View). 如何通过 XML 布局文件传递这些函数,例如android:onClick="methodName"我们可以从活动或视图模型的上下文中传递函数,以便在单击这些按钮时调用传递的方法。是否可以创建自定义属性,例如onCreate?我知道创建自定义属性,但我一直在获取和调用从上下文传递的函数。

标签: javaandroidandroid-layoutkotlinandroid-custom-view

解决方案


当您使用视图模型时,可能会意识到数据绑定,它可以帮助您将视图模型传递给 xml。

以防万一DataBinding的小指导

现在您的自定义视图 xml 从顶部看起来应该像这样

 <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto">

        <data>
            <variable
                name="viewModel"
                type="com.samples.LoginViewModel" />
        </data>
      <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="20dp">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            tools:fontPath=""
            android:onClick="@{(v) -> viewModel.onOkClicked()}"
            android:text="Ok" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:onClick="@{(v) -> viewModel.onCancelClicked()}"
            android:text="Cancel" />

    </LinearLayout>

</layout>

在您的数据类中,您可以像下面这样使用它。

让说你的 xml 名称:custom_view.xml

所以,在你的片段/活动/视图中

val binding: CustomViewBinding = CustomViewBinding.inflate(inflater, container, false)
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = viewModel
binding.executePendingBindings()

让我知道这是否有帮助。


推荐阅读