Fab*_*ian 11 data-binding android android-view
我在我的新应用程序中使用android的数据绑定库.目前我尝试将另一个视图的引用传递给方法.
我有ImageButton一个onClickListener.在这个onClick监听器中,我想将根视图的引用传递给方法.
<RelativLayout
android:id="@+id/root_element"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:contentDescription="@string/close_dialog"
android:src="@drawable/ic_close_212121_24dp"
android:background="@android:color/transparent"
android:onClick="@{() -> Helper.doSth(root_element)}"/>
</RelativLayout>
Run Code Online (Sandbox Code Playgroud)
上面提供的源代码只是一个示例,而不是完整的.有更多的孩子,图像按钮也不是根元素的直接子元素.但我认为意思很清楚.
我已经尝试通过指定根视图的id来传递引用(参见上文).但这不起作用.如果我尝试编译它,我得到错误,root_element没有指定类型.
我还尝试导入生成的绑定类,并通过其中的公共字段访问根元素.此方法也不起作用,因为必须首先生成绑定类.
那么有没有办法将视图的引用传递给方法?我知道我可以传递根视图的id @id/root_element,但是我不希望这样,因为我必须找到一种方法来获得仅使用给定id的对该视图的引用.
Geo*_*unt 51
您可以使用root_element,但Android数据绑定可以使用驼峰名称.因此,root_element成为rootElement.你的处理程序应该是:
android:onClick="@{() -> Helper.doSth(rootElement)}"
Run Code Online (Sandbox Code Playgroud)
你拥有的和你应该做的事之间的区别是,不要传递id root_element.而是将视图作为另一个变量传递到布局文件中.
在我的情况下,我的布局中有一个开关,我想将其作为参数传递给我的lambda中的方法.我的代码是这样的:
MyLayoutBinding binding = DataBindingUtil.inflate(inflater, R.layout.my_layout, parent, true);
binding.setDataUpdater(mDataUpdater);
binding.setTheSwitch(binding.switchFavorite);
Run Code Online (Sandbox Code Playgroud)
然后我的布局是这样的:
<?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="dataUpdater" type="..."/>
<variable name="theSwitch" type="android.widget.Switch"/>
<import type="android.view.View"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{()->dataUpdater.doSomething(theSwitch)}">
<Switch
style="@style/Switch"
android:id="@+id/switch_favorite"
... />
.../>
Run Code Online (Sandbox Code Playgroud)
所以你可以看到,在我的代码中,我获得了对我的开关的引用并将其作为绑定中的变量传递.然后在我的布局中,我可以访问它,在我的lambda中传递它.
| 归档时间: |
|
| 查看次数: |
9063 次 |
| 最近记录: |