[英]Android - How to pass object of a view from XML with data binding
我正在構建一個 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>
請注意在onClick
事件中調用的方法validateOTP()
。 我想將線性布局(otp_container)的視圖 object 作為參數發送。 請幫助我為我提供解決方案。
將對象綁定到 XML 的邏輯幾乎相同,在活動/片段 class 中創建這些對象,初始化 XML 文件中的相應變量並使用綁定變量。
嘗試以下
活動 class
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
必須對視圖一無所知,因為如果活動/片段被破壞/重新創建,視圖組中的視圖引用將導致 memory 泄漏
要傳遞單擊的視圖,您可以這樣做
android:onClick="@{(view)->viewModel.onOthers(view)}"
要傳遞單擊視圖以外的視圖,請傳遞 id,
android:onClick="@{(view)->viewModel.onOthers(otpContainer)}"
請注意,方法的簽名應該像
fun onOthers(view:View){
//your code goes here
}
這樣它就可以允許任何類型的視圖。
更新otp_container
將是otpContainer
用於Binding
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.