Material 목록-세부정보 레시피

이 레시피에서는 Material 3 적응형 라이브러리의 ListDetailSceneStrategy를 사용하여 적응형 목록-세부정보 레이아웃을 만드는 방법을 보여줍니다. 이 레이아웃은 사용 가능한 화면 너비에 따라 하나, 두 개 또는 세 개의 창을 표시하도록 자동으로 조정됩니다.

작동 방식

이 예시에는 ConversationList, ConversationDetail, Profile의 세 가지 대상이 있습니다.

ListDetailSceneStrategy

이 레시피의 핵심은 적응형 레이아웃의 로직을 제공하는 rememberListDetailSceneStrategy입니다.

  • 창 역할: 각 대상에는 메타데이터를 사용하여 역할이 할당됩니다.

    • ListDetailSceneStrategy.listPane(): 기본 (목록) 콘텐츠용입니다. 이 창은 항상 표시됩니다. 세부정보 콘텐츠가 선택되지 않은 경우 세부정보 창 영역에 표시할 자리표시자를 제공할 수 있습니다.
    • ListDetailSceneStrategy.detailPane(): 보조 (세부정보) 콘텐츠용입니다.
    • ListDetailSceneStrategy.extraPane(): 3차 콘텐츠용입니다.
  • 적응형 레이아웃: ListDetailSceneStrategy에서 레이아웃을 자동으로 처리합니다. 작은 화면에서는 한 번에 하나의 창만 표시됩니다. 더 넓은 화면에서는 목록 창과 세부정보 창이 나란히 표시됩니다. 매우 넓은 화면에서는 목록, 세부정보, 추가 등 세 개의 창을 모두 표시할 수 있습니다.

  • 탐색: 창 간 탐색은 평소와 같이 백 스택에서 대상을 추가하고 삭제하여 처리됩니다. ListDetailSceneStrategy는 백 스택을 관찰하고 그에 따라 레이아웃을 조정합니다.

package com.example.nav3recipes.material.listdetail

/*
 * Copyright 2025 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.adaptive.ExperimentalMaterial3AdaptiveApi
import androidx.compose.material3.adaptive.currentWindowAdaptiveInfoV2
import androidx.compose.material3.adaptive.layout.calculatePaneScaffoldDirective
import androidx.compose.material3.adaptive.navigation3.ListDetailSceneStrategy
import androidx.compose.material3.adaptive.navigation3.rememberListDetailSceneStrategy
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.dropUnlessResumed
import androidx.navigation3.runtime.NavKey
import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.runtime.rememberNavBackStack
import androidx.navigation3.ui.NavDisplay
import com.example.nav3recipes.content.ContentBlue
import com.example.nav3recipes.content.ContentGreen
import com.example.nav3recipes.content.ContentRed
import com.example.nav3recipes.content.ContentYellow
import com.example.nav3recipes.ui.setEdgeToEdgeConfig
import kotlinx.serialization.Serializable

@Serializable
private object ConversationList : NavKey

@Serializable
private data class ConversationDetail(val id: String) : NavKey

@Serializable
private data object Profile : NavKey

class MaterialListDetailActivity : ComponentActivity() {

    @OptIn(ExperimentalMaterial3AdaptiveApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        setEdgeToEdgeConfig()
        super.onCreate(savedInstanceState)

        setContent {

            val backStack = rememberNavBackStack(ConversationList)

            // Override the defaults so that there isn't a horizontal space between the panes.
            // See b/418201867
            val windowAdaptiveInfo = currentWindowAdaptiveInfoV2()
            val directive = remember(windowAdaptiveInfo) {
                calculatePaneScaffoldDirective(windowAdaptiveInfo)
                    .copy(horizontalPartitionSpacerSize = 0.dp)
            }
            val listDetailStrategy = rememberListDetailSceneStrategy<NavKey>(directive = directive)

            NavDisplay(
                backStack = backStack,
                onBack = { backStack.removeLastOrNull() },
                sceneStrategies = listOf(listDetailStrategy),
                entryProvider = entryProvider {
                    entry<ConversationList>(
                        metadata = ListDetailSceneStrategy.listPane(
                            detailPlaceholder = {
                                ContentYellow("Choose a conversation from the list")
                            }
                        )
                    ) {
                        ContentRed("Welcome to Nav3") {
                            Button(onClick = dropUnlessResumed {
                                backStack.add(ConversationDetail("ABC"))
                            }) {
                                Text("View conversation")
                            }
                        }
                    }
                    entry<ConversationDetail>(
                        metadata = ListDetailSceneStrategy.detailPane()
                    ) { conversation ->
                        ContentBlue("Conversation ${conversation.id} ") {
                            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                Button(onClick = dropUnlessResumed {
                                    backStack.add(Profile)
                                }) {
                                    Text("View profile")
                                }
                            }
                        }
                    }
                    entry<Profile>(
                        metadata = ListDetailSceneStrategy.extraPane()
                    ) {
                        ContentGreen("Profile")
                    }
                }
            )
        }
    }
}