java - Android - 创建自定义 xml 属性,如 onClick?
问题描述
我正在尝试创建一个自定义视图,其中包含两个按钮,分别是 OK 和 Cancel。我的视图模型中有两种方法说fun onOkClicked(view View)
和fun onCancelClicked(view View)
. 如何通过 XML 布局文件传递这些函数,例如android:onClick="methodName"
我们可以从活动或视图模型的上下文中传递函数,以便在单击这些按钮时调用传递的方法。是否可以创建自定义属性,例如onCreate
?我知道创建自定义属性,但我一直在获取和调用从上下文传递的函数。
解决方案
当您使用视图模型时,可能会意识到数据绑定,它可以帮助您将视图模型传递给 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()
让我知道这是否有帮助。
推荐阅读
- html - 反应获取错误标识符或字符串文字或预期的数字文字
- java - 从微调器上的项目的值创建视图
- mysql - mariadb(mysql) 慢查询修复
- node.js - 用于登录和注册的微服务模式
- python-2.7 - 通过单击窗口 B 上的按钮关闭窗口 A
- xamarin.forms - 使用 PKCE OAuth 和 .NET API 从 Xamarin Forms 访问 Dropbox - 解决方案
- java - 添加字体未为 acroform 加载正确的 pdfbox
- javascript - 单击链接后关闭下拉菜单并使用过渡
- flutter - 使用 SyncfusionPdf Flutter 进行 Pdf 注释
- android - 如何检查字符串是否以 {SOME_STRING} 开头