Phần 2: Android Bottom Navigation - Jetpack - Destination

Bài viết trả lời 3 câu hỏi:

  • Làm thế nào điều hướng nhiều Fragment trong 1 màn hình Activity?
  • Hiệu ứng khi open/close.

bottom_nav_preview_2

Project sẽ demo việc:

  • Tại màn hình MonsterFragment - Muốn mở màn hình MoneyFragment (màn hình con) - Demo cách 1
  • Tại màn hình SlugFragment - Muốn mở màn hình SlashFragment (màn hình con) - Demo cách 2

Bước 1: Tạo thêm Destination cho 2 fragment mới tương ứng vào file mobie_navigation.xml - file này gọi là Navigation Graph

Ví dụ ở demo sẽ là: navigation_monkey và navigation_slash

Bước 2: Khai báo id navigation mới vào AppBarConfiguration tại MainActivity

Bước 3: Điều hướng có 2 cách:

  • Sử dụng NavController
  • Dùng Navigation Action

NavController - Cách 1#

MonsterFragment điều hướng sang MonkeyFragment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

val options = navOptions {
anim {
enter = R.anim.slide_in_right
exit = R.anim.slide_out_left
popEnter = R.anim.slide_in_left
popExit = R.anim.slide_out_right
}
}

navigateToMonkey?.setOnClickListener {
findNavController().navigate(R.id.navigation_monkey, null, options)
}
}

navigateToMonkey : là id của Button trong XML, nếu bạn dùng

Navigation Action - Cách 2#

bottom_nav_destination

Code điều hướng từ Slug sang Slash trong SlugFragment

1
2
3
4
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navigateToSlash?.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_slash, null))
}

Source code có thể tải về tại Github