使用SafeArgs在片段之间传递数据的问题

问题描述 投票:0回答:1

我想将字符串从一个片段传递到另一个片段。问题是我的HomeFragmentDirections类说我要获得“具有私有访问权”的操作。

Nav_graph.xml:

<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/nav_home">

<fragment
    android:id="@+id/nav_home"
    android:name="com.example.chronosaur.ui.HomeFragment"
    android:label="Home"
    tools:layout="@layout/fragment_home">
    <action
        android:id="@+id/action_add_data"
        app:destination="@+id/addDataFragment" />
</fragment>
<fragment
    android:id="@+id/nav_diagram"
    android:name="com.example.chronosaur.ui.DiagramsFragment"
    android:label="fragment_diagrams"
    tools:layout="@layout/fragment_diagrams" />
<fragment
    android:id="@+id/nav_shop"
    android:name="com.example.chronosaur.ui.ShopFragment"
    android:label="fragment_shop"
    tools:layout="@layout/fragment_shop"/>
<fragment
    android:id="@+id/addDataFragment"
    android:name="com.example.chronosaur.ui.AddDataFragment"
    android:label="Add data"
    tools:layout="@layout/fragment_add_data" >
    <argument
        android:name="currentDate"
        app:argType="string"
        android:defaultValue="default" />
</fragment>

HomeFragment:

 String currentDate = "hello";
 @Override
 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
 super.onActivityCreated(savedInstanceState);

 btn_add = getActivity().findViewById(R.id.btn_add);
 btn_add.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        HomeFragmentDirections.ActionAddData() action = new HomeFragmentDirections.ActionAddData(); 
     // error in this string
        action.setCurrentDate(currentDate);
        Navigation.findNavController(v).navigate(action);

      }
    });
   }

错误,它不允许我启动应用程序:

error: ActionAddData() has private access in ActionAddData

我该如何解决问题?感谢您的帮助。

java android android-fragmentactivity android-safe-args
1个回答
0
投票

动作应定义如下:

HomeFragmentDirections.ActionAddData action = HomeFragmentDirections.actionAddData();
            action.setCurrentDate(currentDate);
            Navigation.findNavController(v).navigate(action);
© www.soinside.com 2019 - 2024. All rights reserved.