我将视图模型中的侦听器绑定到片段 xml 中 FAB 的单击。
我的片段 xml 显示了 FAB。
<data>
<variable
name="vehicleViewModel"
type="com.buildit4me.autonance.ui.VehicleViewModel" />
<variable
name="launcher"
type="androidx.activity.result.ActivityResultLauncher" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fabVehicles"
android:contentDescription="@string/fab_content_description"
style="@style/FAB"
android:onClick="@{(view) -> vehicleViewModel.FabOnClick(view,launcher)}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
我的 Viewmodel 监听器
public void FabOnClick( View view, ActivityResultLauncher<Intent> launcher){
Intent intent= new Intent(view.getContext(), AddNewEntityActivity.class);
intent.putExtra(getApplication().getResources().getString(R.string.fragmentID), R.layout.fragment_add_vehicle);
launcher.launch(intent);
}
在我的片段中
ActivityResultLauncher<Intent> launcher= registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<>() {
@Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode()== Activity.RESULT_OK){
mVehicleViewModel.getAllVehicles();
}
String msg;
try {
msg = result.getData().getStringExtra(getResources().getString(R.string.intent_msg));
}
catch( NullPointerException e){
msg=null;
}
Utils.displaySnackbar(binding.recyclerviewVehicles,binding.fabVehicles,msg);
}
});
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding= DataBindingUtil.inflate(inflater,R.layout.fragment_vehicles,container,false);
mVehicleViewModel = new ViewModelProvider(requireActivity()).get(VehicleViewModel.class);
binding.setVehicleViewModel(mVehicleViewModel);
binding.setLauncher(launcher);
我构建项目时的错误。
[databinding] {"msg":"cannot find method FabOnClick(android.view.View, androidx.activity.result.ActivityResultLauncher) in class com.buildit4me.autonance.ui.VehicleViewModel","file":"app/src/main/res/layout/fragment_vehicles.xml","pos":[{"line0":30,"col0":37,"line1":30,"col1":78}]}
我尝试使缓存失效以清除生成的绑定文件,但仍然收到错误。
我认为问题的原因在于XML(androidx.activity.result.ActivityResultLauncher)和Fragment(ActivityResultLauncher
)中的
launcher
您可以尝试替代解决方案。不绑定ActivityResultLauncher,使用该实例内部片段。
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fabVehicles"
android:contentDescription="@string/fab_content_description"
style="@style/FAB"
android:onClick="@{(view) -> vehicleViewModel::FabOnClick}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
片段中
public void FabOnClick(){
Intent intent= new Intent(getContext(), AddNewEntityActivity.class); // Can use context of fragment
intent.putExtra(getApplication().getResources().getString(R.string.fragmentID), R.layout.fragment_add_vehicle);
launcher.launch(intent);
}
希望有帮助