Android 无需点击按钮的片段导航

Android fragment navigation without button click

我正在使用一个使用片段的 "Drawer Navigation" 项目,到目前为止这个方法有效:

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Navigation.findNavController(view).navigate(R.id.nav_gallery);
        }
    });

但我想在片段中使用导航方法 class 调用这样的函数:

boolean b;
public void fragmentNavigation() {
    if (b) {
        Navigation.findNavController(getView()).navigate(R.id.nav_gallery);
    } 
}

我是使用导航架构的新手,我仍然不知道是否需要为该功能声明某种类型的动作侦听器或如何使其工作。

你可以这样做,但要小心:

  1. using getView() is Nullable; so you must make sure that your fragment has already created the view.

您可以通过几种方法解决这个问题

首先: 覆盖具有非空视图参数的 onViewCreated()

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    fragmentNavigation(view);

}
boolean b;
public void fragmentNavigation(View view) {
    if (b) {
        Navigation.findNavController(view).navigate(R.id.nav_gallery);
    } 
}

其次:在片段class中创建View字段,并在onCreateView()

内设置
View view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.main_fragment, container, false);
    return view;
}

然后始终在该视图字段上调用 ​​fragmentNavigation(view);

  1. Your fragment is hosted by the NavHostFragment of the Navigation Graph; so that you can avoid potential IllegalStateException