0

我正在使用带有安全参数的 android 导航组件。我将参数设置为可以为空,默认值也为空。

问题是当我想传递任何值时会显示错误:

required: no arguments
found: Character
reason: actual and formal argument lists differ in length

我的片段 XML 代码:

<fragment
        android:id="@+id/bookListFragment"
        android:name="com.example.bookstory.UI.Fragments.BookListFragment"
        android:label="fragment_book_list"
        tools:layout="@layout/fragment_book_list">
            <argument
            android:name="character"
            app:argType="com.example.bookstory.DAO.Character"
            app:nullable="true"
            android:defaultValue="@null" />
</fragment>

我的行动:

      <action
            android:id="@+id/action_bookDescriptionFragment_to_bookListFragment"
            app:destination="@id/bookListFragment"
            app:popUpTo="@id/bookListFragment"
            app:popUpToInclusive="true" />

我不明白问题出在哪里 - 当我删除默认值时就可以了。

4

2 回答 2

0

ClassNameDirections.ActionName action = ClassNameDirections.actionName(character); Navigation.findNavController(v).navigate(action);

因为您的操作 ID 是action_bookDescriptionFragment_to_bookListFragment

  <action
        android:id="@+id/action_bookDescriptionFragment_to_bookListFragment"

然后可以在这个接受arg的navigate()方法版本中使用它:NavDirections

findNavController().navigate(BookListFragmentDirections.actionBookDescrioptionFragmentToBookListFragment()

这不会传递值,但要这样做:

因为您的值被命名为character

 <argument
        android:name="character"
        app:argType="com.example.bookstory.DAO.Character"
        app:nullable="true"
        android:defaultValue="@null" />

然后您可以使用 safeArgs 生成的setCharacter()方法级联操作:

findNavController().navigate(BookListFragmentDirections.actionBookDescrioptionFragmentToBookListFragment()
                    .setCharacter("c")

我看到您使用 safeArgs,但以防万一您不想使用它;您可以使用此 navigate()方法版本通过捆绑对象设置值

于 2021-10-02T14:25:50.037 回答
0

我不知道 safeArgs,但如果你没有使用 safeArgs 得到答案,这就是你使用普通捆绑包的方式。

如果您不知道,您可以沿着导航操作发送一个包含您的数据的包,作为该方法的第二个参数。
像那样

char char_value = 'a' ;
Bundle data = new Bundle() ;
data.putChar("key",char_value);
NavHostFragment.findNavController(this)
                    .navigate(R.id.action_bookDescriptionFragment_to_bookListFragment,data);

在 booklistFragment 中,您只需在片段内的任何位置调用 getArguments() 即可获得这样的捆绑包

public class BookListFragment extends Fragment {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
    Bundle data = getArguments() ;
    char receivedChar = data.getChar("key",'z'); // 'z' is a default value incase it didn't find the key you're looking for it returns 'z'
    }

您可以在其中捆绑各种东西,只需键入“put”并查看 AutoComplete 的建议。

如果使用捆绑包,则无需argument在 nav_graph xml 中添加该部分。

于 2021-10-02T13:29:30.200 回答