1

我的片段中有一个按钮,可以打开一个 BottomSheetDialogFragment。如果用户在 BottomSheetDialogFragment 上选择了一个项目,我想通知主机片段。为了实现这一点,我在我的 BottomSheetDialogFragment 中做了一个接口。但是,该接口仅与宿主活动通信,而不与片段通信。如何将对话框中的信息发送到片段?

这是我的界面:

public interface BottomSheetListener {
        void onButtonClicked(int index);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        try {
            mListener = (BottomSheetListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() + " must implement BottomSheetListener");
        }
    }
4

2 回答 2

3

getParentFragment将返回父fragment,如果当前fragment附加到fragment,否则返回null,如果它直接附加到Activity

@Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        try {
            mListener = (BottomSheetListener) getParentFragment();
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() + " must implement BottomSheetListener");
        }
    }
于 2021-01-19T18:09:57.663 回答
2

当您使用大量片段、嵌套片段或对话片段时,它们之间的通信会变得混乱。我建议使用 ViewModel 和 LiveData 来传递和更新数据。

首先将其添加到构建 gradle :

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'

然后创建 ViewModel 类:

公共类 YourViewModel 扩展 AndroidViewModel {

private MutableLiveData<Integer> yourMutableLiveData=new MutableLiveData<>();

public YourViewModel(@NonNull Application application) {
    super(application);
}

public MutableLiveData<Integer> getYourMutableLiveData() {
    return yourMutableLiveData;
}

}

这是您要设置值的片段:

   public class FragmentA extends Fragment{

        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

            YourViewModel yourViewModel =new ViewModelProvider(getActivity()).get(YourViewModel.class);

            yourViewModel.getYourMutableLiveData().setValue(0);
        }
    }

这是您希望在更新时获得价值的片段:

 public class FragmentB extends Fragment{

        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

            YourViewModel yourViewModel =new ViewModelProvider(getActivity()).get(YourViewModel.class);

            yourViewModel.getYourMutableLiveData().observe(getViewLifecycleOwner(), new Observer<Integer>() {
                @Override
                public void onChanged(Integer integer) {

                }
            });
        }
    }

它可以在我测试的对话框片段上工作。

注意:-不要将上下文或任何视图传递到视图模型中。

- 请记住 onActivityCreated 在 onCreateView 之后。

-不要将此键设置为

 YourViewModel yourViewModel =new ViewModelProvider(this).get(YourViewModel.class);

如果您想将数据片段传递给片段,则在片段中,但您可以传递活动。

- 您可以为数据设置多个观察者。

于 2021-01-19T19:24:47.610 回答