在Fragment的onActivityCreated方法中手动触发一次绑定。在绑定时,需要将LifecycleOwner设置为Fragment的viewLifecycleOwner。
代码示例:
public class MyFragment extends Fragment {
private FragmentMyBinding binding;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_my, container, false);
return binding.getRoot();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
binding.setViewModel(viewModel);
binding.setLifecycleOwner(this.getViewLifecycleOwner());
binding.executePendingBindings();
}
}