问题描述
我有3个底部导航选项卡,称为Home, Dashboard, Profile
.
I have 3 bottom navigation tabs called Home, Dashboard, Profile
.
- 在
Home
中,我有Fragment1
和Fragment2
, - 在
Dashboard
中,我有Fragment3
和Fragment4
- 在
Profile
中,我有MyProfile
和EditProfile
.
- In
Home
, I haveFragment1
andFragment2
, - In
Dashboard
, I haveFragment3
andFragment4
- And in
Profile
, I haveMyProfile
andEditProfile
.
现在,在Fragment2
中,按钮changeAvatar
可以打开堆栈Profile
中的EditProfile
.因为EditProfile
应该在选项卡Profile
中,所以如果我不想在Home
的navGraph
中包含EditProfile
,我该如何实现这种行为?
Now, in Fragment2
, a button changeAvatar
can open EditProfile
in stack Profile
. Because EditProfile
should be in tab Profile
, so if I don't want to include EditProfile
into navGraph
of Home
, how can I achieve that behavior?
推荐答案
要从主页> Fragment2 导航到 Profile> EditProfile ,您可以使用Navigation
.
To navigate from Home > Fragment2 to Profile > EditProfile you can pass an id by edit type using Navigation
.
private fun navigateToEditProfileAvatar() {
buttonEditProfileAvatar.setOnClickListener { button ->
Navigation.findNavController(button).navigate(
R.id.action_global_to_edit_profile,
RootNavigationDirections.actionGlobalToEditProfile(
editType = EditType.EDIT_PROFILE_AVATAR.id
).arguments
)
}
}
EditProfileFragment.kt
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
...
viewModel.setEditTypeId(EditProfileFragmentArgs.fromBundle(arguments ?: Bundle()).editType)
}
private fun bind() {
when (viewModel.editTypeId) {
EditType.EDIT_PROFILE.id -> { ... }
EditType.EDIT_PROFILE_AVATAR.id -> {
// here
}
}
}
EditProfileVM.kt
val editTypeId = MutableLiveData<String>()
fun setEditTypeId(id: editTypeId ) {...}
res/navigation/root_navigation.xml
<action
android:id="@+id/action_global_to_edit_profile"
app:destination="@id/edit_profile_fragment" />
<fragment
android:id="@+id/edit_profile_fragment"
android:name="EditProfileFragment"
android:label=" "
tools:layout="@layout/fragment_edit_profile">
<argument
android:name="editType"
app:argType="string"
android:defaultValue="@string/edit_profile"
/>
</fragment>
EditType.kt
enum class EditType(val id: String) {
EDIT_PROFILE("EDIT_PROFILE"), EDIT_PROFILE_AVATAR("EDIT_PROFILE_AVATAR");
}
注意:导航的参数不能为枚举类型
Note: The arguments of a navigation cannot be of type Enum
GL
这篇关于如何使用导航组件切换到不同后堆栈中的其他片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!