如何使用 SafeArgs 导航

How to navigate using SafeArgs

我刚开始使用 Jetpack Navigation 组件和 SafeArgs 在 Android 中进行导航。但是,我不明白如何从一个目的地导航到另一个目的地(我阅读了 google 文档,但这让我感到困惑)。所以我有一个 Menu_Fragment class,在 NavGraph 中有一个 link 到一个 Softdrink class。 Menu_Fragment方向 class 已自动创建。但是,我不知道如何使用它在Menu_Fragment class 内实现一个OnClick 侦听器事件。这里我在 Menu_Fragment class 中有 onClick 方法(参见 https://developer.android.com/guide/navigation/navigation-navigate):

@Override
public void onClick(View view) {

    if(view.getId() == R.id.imageButton_Softdrinks_en) {
        float amount = ...;
        action =
                Menu_FragmentDirections
                        .actionMenuFragmentToSoftdrinks(amount);
        Navigation.findNavController(view).navigate(action);

    }

}

在这里您可以看到Menu_Fragment路线class:

package com.example.td.barapp;

import androidx.annotation.NonNull;
import androidx.navigation.ActionOnlyNavDirections;
import androidx.navigation.NavDirections;

public class Menu_FragmentDirections {
  private Menu_FragmentDirections() {
  }

  @NonNull
  public static NavDirections actionMenuFragmentToSoftdrinks() {
    return new ActionOnlyNavDirections(R.id.action_menu_Fragment_to_softdrinks);
  }
}

在这里您可以看到 NavGraph:

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/nav_graph"
    app:startDestination="@id/menu_Fragment">

    <fragment
        android:id="@+id/menu_Fragment"
        android:name="com.example.td.barapp.Menu_Fragment"
        android:label="fragment_menu_"
        tools:layout="@layout/fragment_menu" >
        <action
            android:id="@+id/action_menu_Fragment_to_softdrinks"
            app:destination="@id/softdrinks" />
    </fragment>
    <fragment
        android:id="@+id/softdrinks"
        android:name="com.example.td.barapp.Softdrinks"
        android:label="fragment_softdrinks"
        tools:layout="@layout/fragment_softdrinks" />
</navigation>

任何人都可以告诉我,我必须在发布的 onCreateMethod() 中做什么 above.I 得到错误消息: “无法解析符号 'action'”和“无法解析符号 'Navigation'”(当然还有使用意外标记“...”的错误)

非常感谢您的每条评论,也非常感谢您的帮助。

此处更新是完整的 Menu_Fragment class 与 onCreateMethod:

package com.example.td.barapp;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.td.barapp.databinding.FragmentMenuBinding;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link Menu_Fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Menu_Fragment extends Fragment implements View.OnClickListener {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;



    private Menu_Fragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Menu_Fragment.
     */
    // TODO: Rename and change types and number of parameters
    public static Menu_Fragment newInstance(String param1, String param2) {
        Menu_Fragment fragment = new Menu_Fragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }


    }

    private FragmentMenuBinding binding;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentMenuBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.imageButtonCocktailsEn.setOnClickListener(this);
        binding.imageButtonCocktailsAlcfreeEn.setOnClickListener(this);
        binding.imageButtonLongdrinksEn.setOnClickListener(this);
        binding.imageButtonWhiskyEn.setOnClickListener(this);
        binding.imageButtonLiquorEn.setOnClickListener(this);
        binding.imageButtonBeerEn.setOnClickListener(this);
        binding.imageButtonSoftdrinksEn.setOnClickListener(this);
        binding.imageButtonHotDrinksEn.setOnClickListener(this);

    }

    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }


    @Override
    public void onClick(View view) {

        if(view.getId() == R.id.imageButton_Softdrinks_en) {
            float amount = 0f;
            Menu_FragmentDirections.ActionMenuFragmentToSoftdrinks  action = Menu_FragmentDirections
                    .actionMenuFragmentToSoftdrinks(amount);

        }

    }
}

您缺少操作前的对象类型。

喜欢这样:

Menu_FragmentDirections.ActionMenuFragmentToSoftdrinks action = Menu_FragmentDirections
                    .actionMenuFragmentToSoftdrinks(amount);

错误:

error: illegal start of expression float amount = ...;

这是因为你想要一个浮点数,而你传递的是“...”。必须是浮点数

即:float amount = 0.6ffloat amount = 0f.

编辑:

要向片段添加参数,请执行以下步骤:

Select 目标片段并单击突出显示的加号。

之后,选择您想要的变量类型并为其命名

重建您的项目并检查它是否正在运行。

希望对您有所帮助。

Can anybody tell me, what I have to do in the onCreateMethod() posted above.I get the error messages: "Cannot resolve symbol 'action'" and "Cannot resolve symbol 'Navigation'" (and of course the error for using the unexpected token '...')

这是我的想法,您的 navGraph.xml 有问题,您打算将 SafeArg 从 MenuFragment 传递到 SoftDrinksFragment但是您没有编写代码来完成这项工作,这就是为什么您的 action 无法解析的原因。

编辑您的 navGraph.xml 如下:

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/nav_graph"
    app:startDestination="@id/menu_Fragment">

    <fragment
        android:id="@+id/menu_Fragment"
        android:name="com.example.td.barapp.Menu_Fragment"
        android:label="fragment_menu_"
        tools:layout="@layout/fragment_menu" >
        <action
            android:id="@+id/action_menu_Fragment_to_softdrinks"
            app:destination="@id/softdrinks" />
    </fragment>
    <fragment
        android:id="@+id/softdrinks"
        android:name="com.example.td.barapp.Softdrinks"
        android:label="fragment_softdrinks"
        tools:layout="@layout/fragment_softdrinks">
        <argument
            android:name="amount"
            app:argType="integer" />
    </fragment>
    
</navigation>

也解决Navigation的问题 确保将此依赖项添加到您的 gradle 文件

classpath "androidx.navigation:navigation-safe-args-gradle-plugin:.3.0"

将此行添加到 gradle 文件的顶部:

apply plugin: "androidx.navigation.safeargs"