1 /* 2 * Copyright 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package androidx.navigation 18 19 import android.support.annotation.IdRes 20 21 /** 22 * Construct a new [NavGraph] 23 */ 24 inline fun NavigatorProvider.navigation( 25 @IdRes id: Int = 0, 26 @IdRes startDestination: Int, 27 block: NavGraphBuilder.() -> Unit 28 ) = NavGraphBuilder(this, id, startDestination).apply(block).build() 29 30 /** 31 * Construct a nested [NavGraph] 32 */ 33 inline fun NavGraphBuilder.navigation( 34 @IdRes id: Int, 35 @IdRes startDestination: Int, 36 block: NavGraphBuilder.() -> Unit 37 ) = destination(NavGraphBuilder(provider, id, startDestination).apply(block)) 38 39 /** 40 * DSL for constructing a new [NavGraph] 41 */ 42 @NavDestinationDsl 43 class NavGraphBuilder( 44 val provider: NavigatorProvider, 45 @IdRes id: Int, 46 @IdRes private var startDestination: Int 47 ) : NavDestinationBuilder<NavGraph>(provider[NavGraphNavigator::class], id) { 48 private val destinations = mutableListOf<NavDestination>() 49 50 /** 51 * Build and add a new destination to the [NavGraphBuilder] 52 */ 53 fun <D : NavDestination> destination(navDestination: NavDestinationBuilder<D>) { 54 destinations += navDestination.build() 55 } 56 57 /** 58 * Adds this destination to the [NavGraphBuilder] 59 */ 60 operator fun NavDestination.unaryPlus() { 61 addDestination(this) 62 } 63 64 /** 65 * Add the destination to the [NavGraphBuilder] 66 */ 67 fun addDestination(destination: NavDestination) { 68 destinations += destination 69 } 70 71 override fun build(): NavGraph = super.build().also { navGraph -> 72 navGraph.addDestinations(destinations) 73 if (startDestination == 0) { 74 throw IllegalStateException("You must set a startDestination") 75 } 76 navGraph.startDestination = startDestination 77 } 78 } 79