java使用数据绑定库绑定需要其他组件的事件
我刚刚学习了Android Java的数据绑定。所以我在活动中也是这样做的
activityAddOverTimeBinding = DataBindingUtil
.setContentView(this, R.layout.activity_add_over_time);
activityAddOverTimeBinding.setOvertime(overTime);
handlers = new AddOvertimeClickHandlers(this);
activityAddOverTimeBinding.setClickHandler(handlers);
在这个活动中创建了一个内部类,如下所示:
public class AddOvertimeClickHandlers{
private Context context;
public AddOvertimeClickHandlers(Context context) {
this.context = context;
}
public void onSubmitButtonClick(View v){
Toast.makeText(context, "Button Clicked", Toast.LENGTH_SHORT).show();
}
}
在我的xml中,我这样做:
<data>
<variable
name="overtime"
type="com.anushka.安卓tutz.contactmanager.db.entities.OverTimeDto" />
<variable
name="click_handler"
type="com.sample.安卓.overtimetracker.userinterfaces.AddOverTime.AddOvertimeClickHandlers" />
</data>
<Button
安卓:id="@+id/btnSubmit"
style="@style/Widget.AppCompat.Button.Colored"
安卓:layout_width="match_parent"
安卓:layout_height="58dp"
安卓:layout_marginStart="32dp"
安卓:layout_marginLeft="32dp"
安卓:layout_marginTop="32dp"
安卓:layout_marginEnd="32dp"
安卓:layout_marginRight="32dp"
安卓:text="@string/submit_button"
安卓:onClick="@{click_handler::onSubmitButtonClick}"
安卓:textColorLink="@color/colorPrimaryDark"
安卓:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.605"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/linearLayout2" />
这确实有效。但我担心的是;既然click处理程序在另一个类中,那么我如何访问活动的不同组件呢?因为这是我点击按钮时逻辑的一部分?为了更好地说明这一点,下面是我在不将“点击处理程序”放在另一个类上的情况下编写的代码
activityAddOverTimeBinding.btnSubmit.setOnClickListener(v -> {
if (TextUtils.isEmpty(overTime.getTitle())) {
Toast.makeText(getApplicationContext(), "Title cannot be empty", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(overTime.getDescription())) {
Toast.makeText(getApplicationContext(), "Description cannot be empty", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(overTime.getStartDate())) {
Toast.makeText(getApplicationContext(), "Start time cannot be empty", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(overTime.getEndDate())) {
Toast.makeText(getApplicationContext(), "End time cannot be empty", Toast.LENGTH_SHORT).show();
} else {
String title = overTime.getTitle();
String description = overTime.getDescription();
String startTime = overTime.getStartDate();
String endTime = overTime.getEndDate();
Intent intent = new Intent();
intent.putExtra("title", title);
intent.putExtra("description", description);
intent.putExtra("startTime", startTime);
intent.putExtra("endTime", endTime);
setResult(RESULT_OK, intent);
finish();
}
});
overTime
对象在我的活动类中,它是“DataInded”。因此,我的AddOvertimeClickHandlers类不知道它是否已更改或是否有值。即使我把OverTime
类放在构造函数中,如果这个对象在我的活动类中发生了变化,它也不会改变。也许我可以使用一个接口,这样超时对象也会在AddOvertimeClickHandlers中更新,但这会使我的程序比仅仅将整个事件侦听器放在活动类中并跳过AddOvertimeClickHandlers更复杂。我这样想对吗?你能告诉我怎么做吗?谢谢
# 1 楼答案
只要通过数据绑定发生单击,就可以获取
overtime
的任何当前值只需更新以下代码:
Xml:
这样,您的侦听器/处理程序
AddOvertimeClickHandlers
就有了对函数调用执行内部逻辑所需的参数