android - Android - 如何通过数据绑定从 XML 传递视图对象
问题描述
我正在构建一个使用数据绑定库的 Android 应用程序。我对Data binding
概念并不陌生,正在寻找以下解决方案
有一个名为otp_validation.xml的布局文件
<data>
<variable
name="otpViewModel"
type="dial.to.go.otp.OTPViewModel" />
</data>
<ConstraintLayout
.....................
.....................
.....................
<LinearLayout
android:id="@+id/otp_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/_20sdp"
android:orientation="horizontal"
android:weightSum="4">
<androidx.appcompat.widget.AppCompatEditText
android:layout_width="@dimen/_40sdp"
android:layout_height="@dimen/_50sdp"
android:layout_weight="1"
android:background="@drawable/all_edit_selector"
android:gravity="center"
android:inputType="number"
android:maxLength="1"
android:textSize="@dimen/_22sdp" />
<androidx.appcompat.widget.AppCompatEditText
android:layout_width="@dimen/_40sdp"
android:layout_height="@dimen/_50sdp"
android:layout_marginLeft="@dimen/_8sdp"
android:layout_weight="1"
android:background="@drawable/all_edit_selector"
android:gravity="center"
android:inputType="number"
android:maxLength="1"
android:textSize="@dimen/_22sdp" />
</LinearLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="@dimen/_30sdp"
android:background="@color/colorPrimary"
android:backgroundTint="@color/colorPrimary"
<!-- I want to pass the view object of otp container as a parameter in the method validateOTP()
android:onClick="@{() -> otpViewModel.validateOTP()}"
android:src="@drawable/drawable_fab_proceed"
app:borderWidth="0dp"
app:fabSize="normal"
app:rippleColor="@color/colorAccent" />
</ConstraintLayout>
请注意事件validateOTP()
中调用的方法。onClick
我想将线性布局(otp_container)的视图对象作为参数发送。请帮助我为我提供解决方案。
解决方案
将对象绑定到 XML 的逻辑几乎相同,在活动/片段类中创建这些对象,在 XML 文件中初始化相应的变量并使用绑定来绑定对象和变量。
尝试以下
活动课
val yourLinearLayout = findViewById<View>(R.id.otp_container)
binding.view = yourLinearLayout
XML 文件
<data>
<variable
name="otpViewModel"
type="dial.to.go.otp.OTPViewModel" />
<variable
name = "view"
type = "android.widget.LinearLayout"
</data>
//rest of the logic
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
..........
..........
android:onClick="@{() -> otpViewModel.validateOTP(view)}"
..........
........./>
虽然它有效,但它确实是一种不好的做法。Viewgroup
必须对视图一无所知,因为如果活动/片段被破坏/重新创建,视图组中的视图引用将导致内存泄漏
推荐阅读
- javascript - 在 reducer (redux) 中使用拼接
- python - 使用scrapy从表格行(tr)中提取td文本的问题
- django - Django中的错误上传路径
- blazor - 在 Blazor 中绑定完成后如何运行其他操作?
- c++ - mongo-cxx-driver 十进制值问题
- python - 为什么代码不只是对正数求和?
- dpi - 从 Inkscape 0.91 升级到 0.92 或更高版本会破坏对象 dpi 缩放
- laravel - 包含来自模型和数据透视表 laravel 的数据的周历
- maven - 在 Maven 中运行测试阶段,同时跳过验证和编译
- r - R中的多个时间序列图