首次设置导航组件

Setting up Navigation components for the first time

我正在尝试使用 Navigation components,但出现以下错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.menus/com.example.menus.NavHostFragment}: java.lang.RuntimeException: com.example.menus.NavHostFragment@af68459 must implement OnFragmentInteractionListener

如您所见,我遗漏了 OnFragmentInteractionListener 并且在该片段的顶部写道:

/** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link RestaurantLogin.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link RestaurantLogin#newInstance} factory method to * create an instance of this fragment. */

如何实施 @link RestaurantLogin.OnFragmentInteractionListenerimplement OnFragmentInteractionListener

我正在使用 java(不是 Kotlin)。

我发现如果删除以下行,应用程序将停止崩溃。

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

改为

@Override
public void onAttach(Context context) {
    super.onAttach(context);
}

不确定这是否可行,但它正在工作。