首页 > 解决方案 > 导航操作未在 Jetpack Navigation 上执行

问题描述

面对 Jetpack Navigation 的一个奇怪问题,任何帮助将不胜感激。我有一个导航图如下:

我想使用喷气背包导航从一个片段导航到其他两个片段。到目前为止,我只能从entry_fragment导航到second_fragment,如下图所示。 导航图

我的 EntryFragment.class :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_entry,container,false);
    v.findViewById(R.id.fragmentOneButton).setOnClickListener(ls);
    v.findViewById(R.id.fragmentTwoButton).setOnClickListener(ls);
    return v;
}

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

private final View.OnClickListener ls = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fragmentOneButton:
                Toast.makeText(getActivity().getApplicationContext(), "First Button", Toast.LENGTH_SHORT).show();
Navigation.createNavigateOnClickListener(R.id.action_entry_fragment_to_first_fragment).onClick(view);
                break;
            case R.id.fragmentTwoButton:
                Toast.makeText(getActivity().getApplicationContext(), "Second Button", Toast.LENGTH_SHORT).show();
                Navigation.createNavigateOnClickListener(R.id.action_entry_fragment_to_second_fragment).onClick(view);
                break;
        }
    }
};

在第一个按钮单击时,我只得到吐司,在单击第二个按钮时,我实际上可以导航到SecondFragment。我在这里做错了什么?以及使用导航进行导航的最佳做法是什么。

提前致谢

标签: javaandroidnavigationandroid-jetpack

解决方案


尝试使用NavHostFragment.findNavController(fragment).navigate(R.id.action_created_from_graph) 而不是 Navigation.createNavigateOnCLickListener

我要忘记我的记忆,所以语法可能有点不对劲,但这就是它的要点。


推荐阅读