【发布时间】:2021-05-23 19:24:41
【问题描述】:
我有一个布局,其中包含一个 edittext 和两个按钮,用于增加和减少 editext 中的值。现在我正在使用include 在我的activity 中使用此按钮,因为我正在多次使用它。
例如:-
<include
android:id="@+id/editTextOne"
layout="@layout/include_edittext_with_buttons"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<include
android:id="@+id/editTextTwo"
layout="@layout/include_edittext_with_buttons"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
我可以获取我的increment 和decrement 按钮的onClick 事件,但我不明白我将如何捕捉到特定include 的onClick 已被点击。 ?
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/editText"
android:layout_width="@dimen/_120sdp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.appcompat.widget.AppCompatImageButton
android:id="@+id/btnPlus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="@dimen/_10sdp"
android:onClick="onClick"
app:layout_constraintBottom_toBottomOf="@id/editText"
app:layout_constraintEnd_toEndOf="@id/editText"
app:layout_constraintTop_toTopOf="@id/editText" />
<androidx.appcompat.widget.AppCompatImageButton
android:id="@+id/btnMinus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/_10sdp"
android:onClick="onClick"
app:layout_constraintBottom_toBottomOf="@id/editText"
app:layout_constraintStart_toStartOf="@id/editText"
app:layout_constraintTop_toTopOf="@id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
注意:- 我使用binding. editTextOne.btnPlus.setOnClickListener { Toast.makeText(this, "Plus", Toast.LENGTH_SHORT).show() } 和其他类似的方法来工作,但我想要的是我可以编写plus 和minus 单击侦听器一次,然后他们更新edittext 的值仅包含它们。
不确定是否有更好的建议?
【问题讨论】:
-
你能分享一下 include_edittext_with_buttons 布局文件吗?
-
不要使用 include Id 在按钮上附加事件,使用按钮或布局 Id 附加 onClickListener。
-
@Ekrem 添加代码
-
@hafiza 我已经在使用按钮 ID,这就是导致问题的原因,因为如果我单击第一个布局的加号按钮,我多次包含相同的布局,那么它也会触发第二个布局的加号按钮,因为它们是相似的
-
在您的情况下,我要做的是创建一个函数,该函数可以获取一个视图(您所包含的特定视图),该视图将初始化它的功能。这样,每次单击按钮都将只属于特定布局的相关子级,并且会节省大量编码(除非您需要为所包含的每个布局提供特定行为)