我有一个片段,可以通过没有参数的底部导航栏导航到,也可以从带有参数的不同片段导航到。导航本身工作得很好,但是一旦我添加了我的参数,它就会崩溃。
我不确定需要多少代码,如果不完整,请见谅:
这是我的导航片段:
<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/homeFragment">
<fragment
android:id="@+id/homeFragment"
android:name="fh.wfp2.flatlife.ui.views.HomeFragment"
android:label="Flatlife"
tools:layout="@layout/home_fragment" />
<fragment
android:id="@+id/todoFragment"
android:name="fh.wfp2.flatlife.ui.views.TodoFragment"
android:label="Todos">
<action
android:id="@+id/action_todoFragment_to_addTodoFragment"
app:destination="@id/addTodoFragment" />
<argument
android:name="taskname"
app:argType="string" />
<argument
android:name="isImportant"
app:argType="boolean" />
</fragment>
<fragment
android:id="@+id/addTodoFragment"
android:name="fh.wfp2.flatlife.ui.views.AddTodoFragment"
android:label="AddTodoFragment">
<action
android:id="@+id/action_addTodoFragment_to_todoFragment"
app:destination="@id/todoFragment" />
</fragment>
</navigation>
这是我的addTodoFragment:
class AddTodoFragment : Fragment(R.layout.add_task_fragment) {
private lateinit var binding: AddTaskFragmentBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = AddTaskFragmentBinding.bind(view)
binding.bAddTodo.setOnClickListener {
if (binding.etAddTodo.text.isNotEmpty()) {
// viewModel.onAddTodoClicked(binding.etAddTodo.text.toString(),
binding.cbImportant.isChecked)
findNavController().navigate(
AddTodoFragmentDirections.actionAddTodoFragmentToTodoFragment(
binding.etAddTodo.text.toString(), binding.cbImportant.isChecked
)
)
} else {
Snackbar.make(it, "The task field can't be empty", Snackbar.LENGTH_SHORT).show()
}
}
}
}
这就是我试图在TodoFragment中获取参数的方式。
private val args: TodoFragmentArgs by navArgs()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
//setting binding and other onClickListeners but they work fine
//reading args
//this i thought would work because then args only get read if not null
args?.let { //debugger stops here and app crashes
if(args.taskname.isNotEmpty())
viewModel.onAddTodoClick(Todo(name = args.taskname, isImportant = args.isImportant))
}
/*second try which I took directly from developers.android but which doesn't make sense in my case i
think because the args could be null I guess
val todoName = args.taskname
val isImportant = args.isImportant
viewModel.onAddTodoClick(Todo(name = todoName, isImportant = isImportant))
*/
}
这是我收到的错误消息:
我希望我的意思很清楚,否则,我会更新问题。这可能会很简单,但我不能完全确定它。