Dải điều hướng

Dải điều hướng cho phép truy cập vào các đích đến trong ứng dụng chạy trên thiết bị có màn hình lớn. Bạn nên sử dụng dải điều hướng cho:

  • Các đích đến cấp cao nhất cần truy cập được ở mọi nơi trong ứng dụng
  • 3 đến 7 điểm đến chính
  • Bố cục cho máy tính bảng hoặc máy tính
Một dải điều hướng dọc ở bên trái màn hình có 4 đích đến (Tất cả tệp, Gần đây, Ảnh và Thư viện), mỗi đích đến có một biểu tượng liên kết và một nút hành động nổi.
Hình 1. Thanh điều hướng có 4 đích đến và một nút hành động nổi.

Trang này hướng dẫn bạn cách hiển thị thanh điều hướng trong ứng dụng bằng các màn hình liên quan và thao tác điều hướng cơ bản.

Nền tảng API

Sử dụng thành phần kết hợp NavigationRail với NavigationRailItem để triển khai thanh điều hướng trong ứng dụng. NavigationRailItem đại diện cho một mục dải nội dung trong cột dải nội dung.

NavigationRailItem bao gồm các thông số chính sau:

  • selected: Xác định xem mục thanh điều hướng hiện tại có được làm nổi bật về mặt hình ảnh hay không.
  • onClick(): Hàm lambda bắt buộc xác định hành động cần thực hiện khi người dùng nhấp vào mục thanh điều hướng. Đây là nơi bạn thường xử lý các sự kiện điều hướng, cập nhật trạng thái mục thanh điều hướng đã chọn hoặc tải nội dung tương ứng.
  • label: Hiển thị văn bản trong mục thanh điều hướng. Không bắt buộc.
  • icon: Hiển thị biểu tượng trong mục thanh điều hướng. Không bắt buộc.

Ví dụ: Điều hướng dựa trên thanh điều hướng dọc

Đoạn mã sau đây triển khai một dải điều hướng để người dùng có thể di chuyển giữa các màn hình trong ứng dụng:

@Composable
fun NavigationRailExample(modifier: Modifier = Modifier) {
    val navController = rememberNavController()
    val startDestination = Destination.SONGS
    var selectedDestination by rememberSaveable { mutableIntStateOf(startDestination.ordinal) }

    Scaffold(modifier = modifier) { contentPadding ->
        NavigationRail(modifier = Modifier.padding(contentPadding)) {
            Destination.entries.forEachIndexed { index, destination ->
                NavigationRailItem(
                    selected = selectedDestination == index,
                    onClick = {
                        navController.navigate(route = destination.route)
                        selectedDestination = index
                    },
                    icon = {
                        Icon(
                            destination.icon,
                            contentDescription = destination.contentDescription
                        )
                    },
                    label = { Text(destination.label) }
                )
            }
        }
        AppNavHost(navController, startDestination)
    }
}

Điểm chính

  • NavigationRail hiển thị một cột dọc gồm các mục thanh điều hướng, trong đó mỗi mục tương ứng với một Destination.
  • val navController = rememberNavController() tạo và ghi nhớ một thực thể của NavHostController, quản lý hoạt động điều hướng trong một NavHost.
  • var selectedDestination by rememberSaveable { mutableIntStateOf(startDestination.ordinal) } quản lý trạng thái của mục thanh điều hướng được chọn.
    • startDestination.ordinal lấy chỉ mục (vị trí) dạng số của mục enum Destination.SONGS.
  • Khi người dùng nhấp vào một mục trên thanh điều hướng, navController.navigate(route = destination.route) sẽ được gọi để chuyển đến màn hình tương ứng.
  • Hàm lambda onClick của NavigationRailItem cập nhật trạng thái selectedDestination để làm nổi bật mục thanh điều hướng được nhấp vào.
  • Hàm này gọi thành phần kết hợp AppNavHost, truyền navController và startDestination để hiển thị nội dung thực tế của màn hình đã chọn.

Kết quả

Hình ảnh sau đây cho thấy kết quả của đoạn mã trước:

Hình 2. Một dải điều hướng chứa 3 đích đến có biểu tượng liên kết: Bài hát, Đĩa nhạc và Danh sách phát.

Bản cập nhật M3 Expressive

Material 3 Expressive ra mắt WideNavigationRail và ModalWideNavigationRail, hỗ trợ trạng thái thu gọn và mở rộng dưới dạng các tuỳ chọn bổ sung bên cạnh NavigationRail tiêu chuẩn.

Hình ảnh cho thấy hai dải điều hướng: một dải thu gọn chỉ hiển thị biểu tượng và một dải mở rộng hiển thị biểu tượng và nhãn.
Hình 3. Dải điều hướng được thu gọn và mở rộng.

Để biết thêm thông tin về các bản cập nhật M3 Expressive cho thanh điều hướng, hãy xem nguyên tắc về thanh điều hướng của Material Design 3.

Dải điều hướng rộng được thu gọn và mở rộng

Thanh điều hướng rộng có hai trạng thái, thu gọn và mở rộng, có thể chuyển đổi cho nhau khi người dùng chọn nút trình đơn. Đoạn mã sau đây minh hoạ cách triển khai WideNavigationRail tạo ảnh động giữa trạng thái thu gọn và mở rộng:

@Composable
fun WideNavigationRailResponsiveSample() {
    var selectedItem by remember { mutableIntStateOf(0) }
    val items = listOf("Home", "Search", "Settings")
    val selectedIcons = listOf(AppIcons.HomeFilled, AppIcons.Search, AppIcons.SettingsFilled)
    val unselectedIcons = listOf(AppIcons.Home, AppIcons.Search, AppIcons.Settings)
    val state = rememberWideNavigationRailState()
    val scope = rememberCoroutineScope()

    Row(Modifier.fillMaxWidth()) {
        WideNavigationRail(
            state = state,
            header = {
                IconButton(
                    modifier =
                        Modifier
                            .padding(start = 24.dp)
                            .semantics {
                                // The button must announce the expanded or collapsed state of the rail
                                // for accessibility.
                                stateDescription =
                                    if (state.currentValue == WideNavigationRailValue.Expanded) "Expanded"
                                    else "Collapsed"
                            },
                    onClick = {
                        scope.launch {
                            if (state.targetValue == WideNavigationRailValue.Expanded) state.collapse()
                            else state.expand()
                        }
                    },
                ) {
                    if (state.targetValue == WideNavigationRailValue.Expanded) {
                        Icon(painter = rememberVectorPainter(AppIcons.MenuOpen), "Collapse rail")
                    } else {
                        Icon(painter = rememberVectorPainter(AppIcons.Menu), "Expand rail")
                    }
                }
            },
        ) {
            items.forEachIndexed { index, item ->
                WideNavigationRailItem(
                    railExpanded = state.targetValue == WideNavigationRailValue.Expanded,
                    icon = {
                        val imageVector =
                            if (selectedItem == index) {
                                selectedIcons[index]
                            } else {
                                unselectedIcons[index]
                            }
                        Icon(
                            painter = rememberVectorPainter(imageVector),
                            contentDescription = null
                        )
                    },
                    label = { Text(item) },
                    selected = selectedItem == index,
                    onClick = { selectedItem = index },
                )
            }
        }

        val textString =
            if (state.currentValue == WideNavigationRailValue.Expanded) "expanded" else "collapsed"
        Column {
            Text(modifier = Modifier.padding(16.dp), text = "The rail is $textString.")
        }
    }
}

Thanh điều hướng mở rộng có thể là thanh điều hướng chuẩn hoặc thanh điều hướng phụ. Cấu hình phương thức chồng lên nội dung chính và mở ra từ biểu tượng trình đơn. Đoạn mã sau đây minh hoạ cách triển khai ModalWideNavigationRail:

@Composable
fun ModalWideNavigationRailSample() {
    var selectedItem by remember { mutableIntStateOf(0) }
    val items = listOf("Home", "Search", "Settings")
    val selectedIcons = listOf(AppIcons.HomeFilled, AppIcons.Search, AppIcons.SettingsFilled)
    val unselectedIcons = listOf(AppIcons.Home, AppIcons.Search, AppIcons.Settings)
    val state = rememberWideNavigationRailState()
    val scope = rememberCoroutineScope()

    Row(Modifier.fillMaxWidth()) {
        ModalWideNavigationRail(
            state = state,
            // Note: the value of expandedHeaderTopPadding depends on the layout of your screen in
            // order to achieve the best alignment.
            expandedHeaderTopPadding = 64.dp,
            header = {
                IconButton(
                    modifier =
                        Modifier
                            .padding(start = 24.dp)
                            .semantics {
                                // The button must announce the expanded or collapsed state of the rail
                                // for accessibility.
                                stateDescription =
                                    if (state.currentValue == WideNavigationRailValue.Expanded) "Expanded"
                                    else "Collapsed"
                            },
                    onClick = {
                        scope.launch {
                            if (state.targetValue == WideNavigationRailValue.Expanded) state.collapse()
                            else state.expand()
                        }
                    },
                ) {
                    if (state.targetValue == WideNavigationRailValue.Expanded)
                        Icon(painter = rememberVectorPainter(AppIcons.MenuOpen), "Collapse rail")
                    else Icon(painter = rememberVectorPainter(AppIcons.Menu), "Expand rail")
                }
            },
        ) {
            items.forEachIndexed { index, item ->
                WideNavigationRailItem(
                    railExpanded = state.targetValue == WideNavigationRailValue.Expanded,
                    icon = {
                        Icon(
                            painter = rememberVectorPainter(if (selectedItem == index) selectedIcons[index] else unselectedIcons[index]),
                            contentDescription = null,
                        )
                    },
                    label = { Text(item) },
                    selected = selectedItem == index,
                    onClick = { selectedItem = index },
                )
            }
        }

        val textString =
            if (state.currentValue == WideNavigationRailValue.Expanded) "expanded" else "collapsed"
        Column {
            Text(modifier = Modifier.padding(16.dp), text = "The rail is $textString.")
        }
    }
}

Dải điều hướng rộng có thể đóng

Trên Android, cử chỉ xem trước thao tác quay lại cho phép người dùng vuốt sang trái hoặc sang phải trên màn hình để quay lại hoặc đóng các thành phần của lớp phủ. Đoạn mã sau đây minh hoạ cách triển khai ModalWideNavigationRail có thể đóng bằng cách đặt hideOnCollapse = true:

@Composable
fun DismissibleModalWideNavigationRailSample() {
    var selectedItem by remember { mutableIntStateOf(0) }
    val items = listOf("Home", "Search", "Settings")
    val selectedIcons = listOf(AppIcons.HomeFilled, AppIcons.Search, AppIcons.SettingsFilled)
    val unselectedIcons = listOf(AppIcons.Home, AppIcons.Search, AppIcons.Settings)
    val state = rememberWideNavigationRailState()
    val scope = rememberCoroutineScope()

    Row(Modifier.fillMaxSize()) {
        ModalWideNavigationRail(state = state, hideOnCollapse = true) {
            items.forEachIndexed { index, item ->
                WideNavigationRailItem(
                    railExpanded = true,
                    icon = {
                        Icon(
                            painter = rememberVectorPainter(if (selectedItem == index) selectedIcons[index] else unselectedIcons[index]),
                            contentDescription = null,
                        )
                    },
                    label = { Text(item) },
                    selected = selectedItem == index,
                    onClick = {
                        selectedItem = index
                        scope.launch { state.collapse() }
                    },
                )
            }
        }

        Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
            val currentPage = items.get(selectedItem)
            Button(onClick = { scope.launch { state.expand() } }, Modifier.padding(32.dp)) {
                Text(text = "$currentPage Page\nOpen modal rail", textAlign = TextAlign.Center)
            }
        }
    }
}

Tài nguyên khác