即使在导航中设置了目标片段的参数值,也无法将值从FragmentOne传递到FragmentTwo



fragment两个片段类代码:

class FragmentTwo : Fragment() {

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
// Inflate the layout for this fragment
val binding : FragmentTwoBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_two, container, false)
var args = FragmentTwoArgs.fromBundle(arguments)
setHasOptionsMenu(true)
return binding.root
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater?.inflate(R.menu.overflow_menu,menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return NavigationUI.onNavDestinationSelected(item!!,findNavController())
|| super.onOptionsItemSelected(item)
}
}

FragmentOne片段类代码:

class FragmentOne : Fragment() {
var nameValue = "Abhas"
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_one, container, false)
val binding: FragmentOneBinding =
DataBindingUtil.inflate(inflater, R.layout.fragment_one, container, false)
binding.clickable = this
binding.button.setOnClickListener {
findNavController().navigate(FragmentOneDirections.actionFragmentOneToFragmentTwo())
}
return binding.root
}
}

导航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/navigation"
app:startDestination="@id/fragmentOne">
<fragment
android:id="@+id/fragmentOne"
android:name="com.example.fragmentpractise1.FragmentOne"
android:label="fragment_one"
tools:layout="@layout/fragment_one" >
<action
android:id="@+id/action_fragmentOne_to_fragmentTwo"
app:destination="@id/fragmentTwo" />
</fragment>
<fragment
android:id="@+id/fragmentTwo"
android:name="com.example.fragmentpractise1.FragmentTwo"
android:label="fragment_two"
tools:layout="@layout/fragment_two" >
<argument
android:name="nameValue"
app:argType="string" />
</fragment>
<fragment
android:id="@+id/aboutFragment"
android:name="com.example.fragmentpractise1.AboutFragment"
android:label="fragment_about"
tools:layout="@layout/fragment_about" />
</navigation>

现在,当我在FragmentTwo类中设置args变量时,在fromBundle中显示错误的args(arguments(。我曾尝试在FragmentOne中的setOnclicklistener中进行导航时给出参数,但它并没有在构造函数中要求任何类型的值。我不明白为什么FragmentTwo类的fromBundle(arguments(中的arguments显示错误。

看起来您忘记在操作中声明参数(片段一(。而且你不会从fragment_one发送任何东西。

您应该在导航xml:中的fragment_one内为操作添加参数

<action
android:id="@+id/action_fragmentOne_to_fragmentTwo"
app:destination="@id/fragmentTwo">
<argument
android:name="nameValue"
app:argType="string"
android:defaultValue="default" />
</action>

然后重新构建应用程序-将生成另一个带有字符串参数的导航操作方法。

FragmentOneDirections.actionFragmentOneToFragmentTwo(nameValue : String)

所以你应该把这个方法的值放在片段一中。

您可以通过链接找到详细的文档。

相关内容

最新更新