
レイアウトのカスタマイズを使用すると、Google 提供のビューと独自のカスタム ビジネスビューの両方で、ビュー階層と画面配置を制御できます。
事前定義されたヘッダーまたはフッターのスロットにカスタムビューを追加するのではなく、レイアウト デリゲートを実装して画面全体のレイアウトを管理します。ナビゲーションの状態遷移中に、レイアウト デリゲートは Google 提供のコンポーネント(ターンカード、到着予定時刻カード、ボタンなど)を受け取ります。ConstraintLayout、CoordinatorLayout、LinearLayout などの標準の Android レイアウト システムを使用して、これらの要素を独自のカスタム コンテンツとともに配置します。
このフレームワークを使用すると、注文ステータスや受け取り手順などのカスタム ビジネス情報を画面上に正確に配置し、ビューが重ならないようにすることができます。
レイアウトのカスタマイズの仕組み
レイアウトのカスタマイズでは、委任デザイン パターンを使用します。SDK は、画面上で UI コンポーネントを自動的に描画または配置するのではなく、作成したカスタムクラス(レイアウト デリゲート)に直接渡します。
レイアウトをカスタマイズするには、抽象NavigationLayoutDelegate クラスを拡張するクラスを作成し、インスタンスを NavigationView または SupportNavigationFragment に割り当てます。ナビゲーションの状態が遷移するたびに(基本地図からアクティブなターンバイターン方式のルート案内への移行など)、SDK はデリゲートのコールバック メソッドを実行し、その特定の状態に使用できる UI コンポーネントを提供します。
シームレスで統合されたユーザー エクスペリエンスを提供するため、このフレームワークでは、アプリと SDK の間で責任を明確に分離しています。レイアウト デリゲートを使用して、以下をカスタマイズします。
- ビュー階層を構築する: 各 UI 状態の画面に追加する Google コンポーネントとカスタム ビジネスビューを正確に選択します。
- すべての要素を配置する: 画面のアンカー、マージン、レイアウトの配置を正確に設定します。Google コンポーネントは独自の内部寸法を計算するため、Google コンポーネントにカスタムの幅または高さの制約を適用しないでください。
- 基本地図をフレームに収める: ビューポート コンポーネントの座標を使用して、地図カメラの表示境界を定義します。
- 画面を重ねる: カスタムビューを Google の組み込みコントロールの上、下、または横に配置するかどうかを決定します。
一方、次の Google コンポーネントは、レイアウト デリゲートでカスタマイズできません。
- コンポーネントのサイズ: Google 提供のコンポーネントのサイズと内部サイズ。SDK によって自動的に計算されます。
- トリガー条件: リアルタイムのルートデータに基づいて、動的なアラートやプロンプトが表示されるタイミング。
実装の原則
レイアウト デリゲートを作成する際は、レイアウトのバグやランタイム クラッシュを防ぐために、次のルールに留意してください。
- デフォルトは空の画面: Google 提供のコンポーネントは、デリゲートが明示的にビュー階層に追加して配置した場合にのみ表示されます。
- 以前の API はサポートされていません。以前のスロットベースのレイアウト モデルを制御するプロパティとメソッドはサポートされません。カスタム デリゲートが有効になっている場合、想定どおりに動作しない可能性があります。
- 内部ビュー構造を変更しない:
findViewById()などのメソッドを使用して、Google 提供のコンポーネント(ターンカードや ETA カードなど)のビュー階層を走査または変更しないでください。これらの内部ビュー階層は、基盤となる実装の詳細であるため、SDK のリリースごとに変更される可能性があります。これらを変更すると、今後の SDK の更新時にレイアウトが破損する可能性があります。
以前の API の互換性
カスタム レイアウト デリゲートを使用する際にレイアウトの動作を安定させるには、以下のレガシー スロットベース API の使用を避けてください。これらの API は非推奨となる予定です。既存のアプリを移行するには、これらの API の使用をカスタム レイアウト デリゲートのコードに置き換えます。
以前のスロットベースの API を表示する
| 以前の API | Layout Delegate の置き換え |
|---|---|
setCustomControl(View, CustomControlPosition) |
ビューを ConstraintLayout または他のビューグループに直接追加します。 |
removeCustomControl(View) |
ビュー階層からビューを直接削除する。 |
setEtaCardEnabled(boolean) |
onEnterActiveGuidance の etaCard ビューを読み取ります。 |
setHeaderEnabled(boolean) |
onEnterActiveGuidance の turnCard ビューを読み取ります。 |
setReportIncidentButtonEnabled(boolean) |
getActiveGuidanceButtons() で REPORTING ボタンを見つけます。 |
setTripProgressBarEnabled(boolean) |
onEnterActiveGuidance の tripProgressBar ビューを読み取ります。 |
addOnNavigationUiChangedListener(...) |
NavigationLayoutDelegate 状態遷移コールバックに依存する。 |
removeOnNavigationUiChangedListener(...) |
デリゲートを使用してレイアウト状態の遷移を直接管理します。 |
addPromptVisibilityChangedListener(...) |
NavigationLayoutDelegate プロンプト コールバック(onShowPrompt() など)を使用します。 |
removePromptVisibilityChangedListener(...) |
デリゲートを使用して、プロンプトの表示ロジックを直接管理します。 |
setCompassEnabled(boolean) |
getNavigationReadyButtons() または getActiveGuidanceButtons() でコンパスを見つけます。 |
Essentials のチェックリスト
レイアウト デリゲートを正常に実装するには、次の重要な手順と要件に従ってください。
-
UI を作成する前にデリゲートを初期化する: SDK がナビゲーション UI を初期化する前に
setLayoutDelegate()を呼び出します。次のコード実装例を参照して、アプリケーション構造の正確な設定タイミングを確認してください。UI の作成後にデリゲートを初期化すると、ApiIllegalStateExceptionがトリガーされます。Kotlin
// For SupportNavigationFragment override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val navFragment = supportFragmentManager.findFragmentById(R.id.nav_fragment) as SupportNavigationFragment navFragment.setLayoutDelegate(MyLayoutDelegate()) } // For a programmatic NavigationView val navigationView = NavigationView(context) navigationView.setLayoutDelegate(MyLayoutDelegate()) navigationView.onCreate(savedInstanceState)
Java
// For SupportNavigationFragment @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SupportNavigationFragment navFragment = (SupportNavigationFragment) getSupportFragmentManager().findFragmentById(R.id.nav_fragment); navFragment.setLayoutDelegate(new MyLayoutDelegate()); } // For a programmatic NavigationView NavigationView navigationView = new NavigationView(context); navigationView.setLayoutDelegate(new MyLayoutDelegate()); navigationView.onCreate(savedInstanceState);
-
独自のレイアウト コンテナを作成する: カスタム UI 要素と Google 提供のビューを保持するカスタムビュー グループ(
ConstraintLayoutなど)を作成します。 -
必須のビューをアタッチする: すべてのナビゲーション状態で、Google ロゴ(
getGoogleLogo())とビューポート(getViewport())をレイアウト コンテナに追加する必要があります。これらのビューを両方とも含めないと、ランタイムApiIllegalStateExceptionがトリガーされ、アプリがクラッシュします。 -
固定サイズを尊重する: SDK は、Google が提供するいくつかのコンポーネントのサイズを決定します。次の要素にカスタムの幅または高さの制約を適用しないでください。
- カードをめくる
- 到着予定時刻カード
- 受信プロンプト
- Google ロゴ
- 速度ウィジェット
-
レイアウトをビューにアタッチする:
onEnterNavigationReady()コールバックとonEnterActiveGuidance()コールバック内でnavigationView.setNavigationLayout()を呼び出して、コンテナをマップビュー階層にアタッチします。 -
状態終了時のクリーンアップ:
onLeaveコールバック内でnavigationView.removeNavigationLayout()を呼び出してカスタムビューを削除し、メモリリークや UI 状態の重複を防ぎます。 -
以前のレイアウト API を使用しない: カスタム デリゲートがアクティブな間は、
setCustomControl()やsetHeaderEnabled()などの非推奨のスロットベースの API を呼び出さないでください。カスタム デリゲートがアタッチされている場合、SDK はこれらの以前の通話機能を無視することがあります。
UI の状態と Google コンポーネント
ナビゲーション状態の遷移が発生すると、SDK は読み取り専用の UiState オブジェクトをデリゲート コールバックに渡します。このオブジェクトは、現在のレイアウト構成フラグと、画面のレンダリングに必要な Google コンポーネント(View インスタンスなど)をバンドルします。
レイアウト デリゲートは、4 つのオペレーション状態にわたってビュー階層を管理します。次の状態図は、SDK がナビゲーション状態間をどのように遷移するか、またデリゲートでどのコールバック メソッドを実行するかを示しています。
デリゲートに提供される特定の Google コンポーネントは、ナビゲーション ライフサイクルの現在のフェーズによって異なります。
必須コンポーネント(すべてのナビゲーション状態)
現在のナビゲーション フェーズに関係なく、次の Google コンポーネントをビュー階層に含めて配置し、表示したままにする必要があります。
Google ロゴ(
getGoogleLogo()): このコンポーネントは、必須の Google マップのロゴを表示します。[中央に再配置] ボタンが有効になっている場合、ドライバーが地図をスクロールして車両から離れると、ロゴが自動的にこのボタンに変わります。そのため、ロゴの配置によって、[Re-center] ボタンが表示される場所が決まります。標準の地図 UI の想定に合わせて、ロゴをレイアウトの左下隅に配置することをおすすめします。ビューポート(
getViewport()): カメラのフレーミング境界を定義する、非表示のView。ビューポートの配置によって、SDK が車両シェブロンを中央に配置し、アクティブなルートラインを描画する場所が決まります。ビューポートを、画面の開いている遮るもののない領域を覆うように配置し、カスタム ボトムシートなどの不透明なオーバーレイを安全に回避します。
ナビゲーション対応コンポーネント
ナビゲーション準備完了状態では、基本地図に集中できるように UI は最小限に抑えられます。NavigationReadyUiState オブジェクトを使用すると、次のものにアクセスできます。
- getNavigationReadyButtons(): 基本地図用に構成されたフローティング アクション ビューのリスト(通常はコンパス ボタンのみ)。Google は今後の SDK リリースでボタンを追加または並べ替える可能性があるため、固定リスト インデックスに依存しないようにしてください。代わりに、リストを反復処理し、
getType()とButtonKnownType.COMPASSを比較して各ボタンのタイプを読み取り、getView()を呼び出して物理ビューを抽出します。このリストのボタンは、アクティブなガイダンス中に使用できるボタンとは異なります。
アクティブ ガイダンス コンポーネント
ターンバイターン方式のルート案内が開始されると、SDK はナビゲーション コントロールの全機能をロック解除します。ActiveGuidanceUiState オブジェクトを使用すると、次の Google コンポーネントにアクセスできます。
getTurnCard(): 次の操作の方向、距離の測定、車線案内を表示するメインのヘッダー バナー。レイアウトの上部に配置して、使い慣れたナビゲーション階層を確立し、その周囲にカスタムビューを固定します。getEtaCard(): 到着予定時刻、残りの移動時間、目的地までの残りの距離を表示するフッター バナー。画面の下端に配置したり、座標をカスタムのタスク管理シートに統合したりできます。getTripProgressBar(): 垂直方向の進行状況バー。現在のルートに沿ってドライバーが移動した距離を示します。以前のレイアウトでは、このボタンは地図の端に固定されていましたが、新しいレイアウトでは、カスタム コンテナの端など、どこにでも固定できます。getSpeedWidget(): 速度計と制限速度の表示を制御するフローティング コントロール。API の設定とデータの可用性に応じて、このビューは実行時に 4 つの表示状態(何も表示しない、現在の速度のみ、速度制限のみ、両方の読み取り値)の間で動的にサイズ変更されます。ウィジェットは予告なくこれらのサイズ間で切り替わる可能性があるため、レイアウトが自動的に調整されて空間的な重複を防ぐように、常に制約を使用して周囲のビューをアンカーします。
getActiveGuidanceButtons(): アクティブなガイダンス状態のフローティング アクション ビューの展開リスト(通常はコンパスと道路状況の報告ボタンの両方を含む)。ナビゲーション準備完了状態と同様に、ButtonKnownType(COMPASSまたはREPORTING)でリストをフィルタリングし、getView()を使用してビューを抽出することで、個々のボタンビューを見つけて抽出できます。その後、それらを個別に配置するか、AutoHidingLinearLayoutなどのレイアウトを使用して、空間的な競合なしに配列を安全にスタックできます。
動的プロンプトのコンポーネント
インシデント アラートや安全カメラの警告などのプロンプトは、アクティブなガイダンス中に個別にトリガーされます。
プロンプトを表示する準備が整うと、SDK はデリゲートの onShowPrompt() コールバックを呼び出し、newPrompt ビューを渡します。デリゲートは、このプロンプトをレイアウト上にスムーズに配置する役割を担います(通常は地図コンテナの下端に固定されます)。
受信プロンプトは画面の下部を覆うため、プロンプトがビューポート、Google ロゴ、下揃えのボタンと重ならないようにレイアウトを更新する必要があります。
画面サイズとワイドモードの処理
地図のサイズと画面の向きの変更を処理するために、レイアウト デリゲートは次の機能を使用します。
ビューのサイズ変更: 地図の物理的なサイズが変更されるたびに、レイアウトを調整します。
ワイドモード: 地図が十分に広い場合、ワイド形式のレイアウト バリアントに切り替えます。
ビューのサイズ変更に対応する
地図コンテナの物理的なサイズが変更されるたびに、SDK はonSizeChanged() コールバックを実行します。分割画面レイアウト、レイアウト スライダー、デバイスの回転は、通常、onSizeChanged() コールバックをトリガーします。このコールバックを使用して、カスタム UI に一般的なレスポンシブ調整を行います。onSizeChanged() を実装して、新しい画面アスペクト比に合わせてカスタム要素を再配置し、独自のカスタム幅または高さのブレークポイントを適用します。また、サイズ変更イベントによってワイドモードが切り替わるタイミングを検出して、レイアウト バリアントを安全に切り替えます。
ワイドモードについて
ワイドモードは、地図コンテナが UI コンポーネントを横並びで表示できる十分な幅がある場合に有効になります。
状態オブジェクトから isWideMode() ブール値を読み取り、カスタム UI 要素の位置を変更して、ドライバーが地図の中心をはっきりと確認できるようにします。Google が提供するコンポーネント(ターンカードや ETA カードなど)は、ワイドモードでは自動的に縮小して形状が変更されるため、このブール値を読み取ることで、Google コンポーネントが更新されるのとまったく同じタイミングでレイアウトが適応されるようになります。
標準モードとワイドモードでレイアウト コンポーネントを配置する例を次に示します。
標準のポートレート モード: 画面の上部にターンカード、下部に ETA カードを配置します。
ワイドモード: ターンカードを画面の開始側に移動し、到着予定時刻カードを終了側に移動します。
状態遷移中のワイドモードの確認
レイアウトがワイドモードのバリエーションをサポートしている場合は、onSizeChanged() のみに依存するのではなく、すべての状態遷移コールバック内で isWideMode() ブール値を評価します。
onEnterNavigationReady() や onEnterActiveGuidance() などのコールバック中に状態オブジェクトをチェックして、横表示モードでのアプリの初回起動を処理します。このアプローチにより、サイズ変更コールバックを完全にバイパスする Android システムのライフサイクル イベント(デフォルトの Activity の再作成など)からレイアウトが保護され、新しい Navigation 状態が開始された時点で、正しい標準レイアウトまたはワイド レイアウトのバリアントが有効になります。
Google のスタイルに合わせる
カスタム UI が Google の視覚的なリズムに合うように、SDK には StyleValues ユーティリティ クラスが用意されています。これらの値を密度非依存ピクセル(dp)で読み取って、ビューを Google コンポーネントに完全に合わせることができます。
たとえば、ターンカードの反対側の画面上部の隅にカスタムボタンを配置する場合は、StyleValues.headerTopPaddingDp() を呼び出して、返された値をボタンの上マージンとして割り当てます。これにより、カスタムボタンがターンカードの上端と視覚的に揃い、画面の対称性が維持されます。
使用可能なスタイル パディングと測定値は次のとおりです。
StyleValues.headerNominalHeightDp()StyleValues.headerTopPaddingDp()StyleValues.headerFooterSidePaddingDp()StyleValues.mapControlSidePaddingDp()StyleValues.buttonMapControlSidePaddingDp()
例: 制約ベースのレイアウトの実装
次の例は、プログラムによる ConstraintLayout と ConstraintSet の定義を使用して状態遷移を管理する基本的なレイアウト デリゲートを示しています。
この例ではコードでビューの制約を構築していますが、レイアウト デリゲートは標準の Android XML レイアウトをインフレートすることもできます。
Kotlin
/* * Copyright 2026 Google LLC * * 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. */ package com.example.navigationapidemo.layoutdelegate import android.content.Context import android.util.TypedValue import android.view.View import android.view.ViewGroup import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintSet import com.google.android.libraries.navigation.layoutcustomization.ActiveGuidanceUiState import com.google.android.libraries.navigation.layoutcustomization.AutoHidingVerticalLayout import com.google.android.libraries.navigation.layoutcustomization.NavigationLayoutDelegate import com.google.android.libraries.navigation.layoutcustomization.NavigationReadyUiState import com.google.android.libraries.navigation.layoutcustomization.NavigationUiButton.ButtonKnownType.COMPASS import com.google.android.libraries.navigation.layoutcustomization.NavigationUiParent import com.google.android.libraries.navigation.layoutcustomization.StyleValues.headerNominalHeightDp /** Kotlin equivalent of StandardUiElementsLayoutDelegate. */ class StandardUiElementsLayoutDelegateKt : NavigationLayoutDelegate() { private val layoutId = View.generateViewId() private val buttonsContainerId = View.generateViewId() private var layout: ConstraintLayout? = null private var buttonsContainer: AutoHidingVerticalLayout? = null private var navigationReadyConstraintSet: ConstraintSet? = null private var activeGuidanceConstraintSet: ConstraintSet? = null private var activeGuidanceWithPromptConstraintSet: ConstraintSet? = null private var activeGuidanceUiState: ActiveGuidanceUiState? = null override fun onEnterNavigationReady( navigationUiParent: NavigationUiParent, newState: NavigationReadyUiState, ) { val context = navigationUiParent.viewContext var currentLayout = layout if (currentLayout == null) { currentLayout = ConstraintLayout(context).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, ) id = layoutId } layout = currentLayout } removeFromParentView(newState.viewport) currentLayout.addView( newState.viewport, ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, ), ) removeFromParentView(newState.googleLogo) currentLayout.addView( newState.googleLogo, ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, ), ) var currentButtonsContainer = buttonsContainer if (currentButtonsContainer == null) { currentButtonsContainer = AutoHidingVerticalLayout(context).apply { id = buttonsContainerId } buttonsContainer = currentButtonsContainer } removeFromParentView(currentButtonsContainer) currentLayout.addView( currentButtonsContainer, ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.MATCH_CONSTRAINT, ), ) for (button in newState.navigationReadyButtons) { removeFromParentView(button.view) currentButtonsContainer.addView(button.view) } if (navigationReadyConstraintSet == null) { navigationReadyConstraintSet = buildNavigationReadyConstraintSet(newState) } navigationReadyConstraintSet?.applyTo(currentLayout) navigationUiParent.removeNavigationLayout(currentLayout) navigationUiParent.setNavigationLayout(currentLayout) } private fun buildNavigationReadyConstraintSet(uiState: NavigationReadyUiState): ConstraintSet { return ConstraintSet().apply { clone(layout) connect( uiState.viewport.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, ) connect(uiState.viewport.id, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP) connect(uiState.viewport.id, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END) connect( uiState.viewport.id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, ) connect( uiState.googleLogo.id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, ) connect( uiState.googleLogo.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, ) constrainButtonsToBottomEnd() } } override fun onLeaveNavigationReady( navigationUiParent: NavigationUiParent, oldState: NavigationReadyUiState, ) { buttonsContainer?.removeAllViews() layout?.removeAllViews() layout?.let { navigationUiParent.removeNavigationLayout(it) } } override fun onEnterActiveGuidance( navigationUiParent: NavigationUiParent, oldState: NavigationReadyUiState, newState: ActiveGuidanceUiState, ) { activeGuidanceUiState = newState val context = navigationUiParent.viewContext val currentLayout = checkNotNull(layout) { "layout must be initialized" } val currentButtonsContainer = checkNotNull(buttonsContainer) { "buttonsContainer must be initialized" } removeFromParentView(newState.turnCard) currentLayout.addView( newState.turnCard, ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, ), ) removeFromParentView(newState.etaCard) currentLayout.addView( newState.etaCard, ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, ), ) for (button in oldState.navigationReadyButtons) { removeFromParentView(button.view) } for (button in newState.activeGuidanceButtons) { val buttonLayoutParams = AutoHidingVerticalLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, ) if (button.type == COMPASS) { buttonLayoutParams.isHighPriority = true } removeFromParentView(button.view) currentButtonsContainer.addView(button.view, buttonLayoutParams) } if (activeGuidanceConstraintSet == null) { activeGuidanceConstraintSet = buildActiveGuidanceConstraintSet(context, newState) } activeGuidanceConstraintSet?.applyTo(currentLayout) } override fun onLeaveActiveGuidance( navigationUiParent: NavigationUiParent, oldState: ActiveGuidanceUiState, newState: NavigationReadyUiState, ) { removeFromParentView(oldState.etaCard) removeFromParentView(oldState.turnCard) buttonsContainer?.removeAllViews() val currentButtonsContainer = checkNotNull(buttonsContainer) { "buttonsContainer must be initialized" } for (button in newState.navigationReadyButtons) { currentButtonsContainer.addView( button.view, ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, ), ) } navigationReadyConstraintSet?.applyTo(layout) } private fun buildActiveGuidanceConstraintSet( context: Context, uiState: ActiveGuidanceUiState, ): ConstraintSet { return ConstraintSet().apply { clone(layout) connect(uiState.turnCard.id, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP) connect( uiState.turnCard.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, ) clear(uiState.viewport.id) connect( uiState.viewport.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, ) connect(uiState.viewport.id, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP) setMargin(uiState.viewport.id, ConstraintSet.TOP, dpToPx(headerNominalHeightDp(), context)) connect(uiState.viewport.id, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END) connect(uiState.viewport.id, ConstraintSet.BOTTOM, uiState.etaCard.id, ConstraintSet.TOP) clear(uiState.googleLogo.id, ConstraintSet.BOTTOM) constrainLogoToTopOfEtaCard(uiState) constrainEtaCardToBottomStart(uiState) constrainButtonsToTopOfEtaCard(context, uiState) } } private fun ConstraintSet.constrainEtaCardToBottomStart(uiState: ActiveGuidanceUiState) { connect(uiState.etaCard.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START) connect(uiState.etaCard.id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM) } private fun ConstraintSet.constrainLogoToTopOfEtaCard(uiState: ActiveGuidanceUiState) { connect(uiState.googleLogo.id, ConstraintSet.BOTTOM, uiState.etaCard.id, ConstraintSet.TOP) } private fun ConstraintSet.constrainButtonsToBottomEnd() { clear(buttonsContainerId, ConstraintSet.BOTTOM) clear(buttonsContainerId, ConstraintSet.TOP) connect(buttonsContainerId, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP) connect(buttonsContainerId, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM) connect(buttonsContainerId, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END) } private fun ConstraintSet.constrainButtonsToTopOfEtaCard( context: Context, uiState: ActiveGuidanceUiState, ) { clear(buttonsContainerId, ConstraintSet.BOTTOM) clear(buttonsContainerId, ConstraintSet.TOP) connect(buttonsContainerId, ConstraintSet.BOTTOM, uiState.etaCard.id, ConstraintSet.TOP) connect(buttonsContainerId, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP) connect(buttonsContainerId, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END) setMargin(buttonsContainerId, ConstraintSet.TOP, dpToPx(headerNominalHeightDp(), context)) } override fun onShowPrompt(navigationUiParent: NavigationUiParent, newPrompt: View) { val context = navigationUiParent.viewContext layout?.addView(newPrompt) if (activeGuidanceUiState != null) { activeGuidanceWithPromptConstraintSet = buildActiveGuidanceWithPromptConstraintSet(context, newPrompt) activeGuidanceWithPromptConstraintSet?.applyTo(layout) } } override fun onChangePrompt( navigationUiParent: NavigationUiParent, oldPrompt: View, newPrompt: View, ) { val context = navigationUiParent.viewContext activeGuidanceWithPromptConstraintSet?.clear(oldPrompt.id) val currentLayout = checkNotNull(layout) { "layout must be initialized" } currentLayout.removeView(oldPrompt) currentLayout.addView(newPrompt) if (activeGuidanceUiState != null) { activeGuidanceWithPromptConstraintSet = buildActiveGuidanceWithPromptConstraintSet(context, newPrompt) activeGuidanceWithPromptConstraintSet?.applyTo(currentLayout) } } override fun onHidePrompt(navigationUiParent: NavigationUiParent, oldPrompt: View) { activeGuidanceWithPromptConstraintSet?.clear(oldPrompt.id) layout?.removeView(oldPrompt) activeGuidanceConstraintSet?.applyTo(layout) } private fun buildActiveGuidanceWithPromptConstraintSet( context: Context, prompt: View, ): ConstraintSet { return ConstraintSet().apply { clone(layout) val state = checkNotNull(activeGuidanceUiState) { "activeGuidanceUiState must be initialized" } clear(state.viewport.id) connect(state.viewport.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START) connect(state.viewport.id, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP) setMargin(state.viewport.id, ConstraintSet.TOP, dpToPx(headerNominalHeightDp(), context)) connect(state.viewport.id, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END) connect(state.viewport.id, ConstraintSet.BOTTOM, prompt.id, ConstraintSet.TOP) clear(state.googleLogo.id, ConstraintSet.BOTTOM) connect(state.googleLogo.id, ConstraintSet.BOTTOM, prompt.id, ConstraintSet.TOP) connect(prompt.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START) connect(prompt.id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM) } } private fun removeFromParentView(view: View?) { if (view?.parent != null) { (view.parent as ViewGroup).removeView(view) } } private fun dpToPx(dp: Int, context: Context): Int { return TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), context.resources.displayMetrics, ) .toInt() } }
Java
/* * Copyright 2026 Google LLC * * 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. */ package com.example.navigationapidemo.layoutdelegate; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static androidx.constraintlayout.widget.ConstraintLayout.LayoutParams.MATCH_CONSTRAINT; import static com.google.android.libraries.navigation.layoutcustomization.NavigationUiButton.ButtonKnownType.COMPASS; import android.content.Context; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.constraintlayout.widget.ConstraintSet; import com.google.android.libraries.navigation.layoutcustomization.ActiveGuidanceUiState; import com.google.android.libraries.navigation.layoutcustomization.AutoHidingVerticalLayout; import com.google.android.libraries.navigation.layoutcustomization.NavigationLayoutDelegate; import com.google.android.libraries.navigation.layoutcustomization.NavigationReadyUiState; import com.google.android.libraries.navigation.layoutcustomization.NavigationUiButton; import com.google.android.libraries.navigation.layoutcustomization.NavigationUiParent; import com.google.android.libraries.navigation.layoutcustomization.StyleValues; /** * A sample implementation of {@link NavigationLayoutDelegate} demonstrating a basic, * portrait-optimized layout using {@link ConstraintLayout}. * * <p><b>Understanding the Layout Delegate State Machine:</b> Navigation SDK transitions through * distinct states, each calling corresponding lifecycle methods on this delegate: * * <ul> * <li><b>Navigation Ready:</b> Initiated by {@link #onEnterNavigationReady}. We initialize the * layout here and add non-guidance views, then pass it to {@link NavigationUiParent} as the * navigation layout. * <li><b>Active Guidance (Turn-by-Turn Mode):</b> Initiated by {@link #onEnterActiveGuidance}. We * set up the layout for Active Guidance, adding elements such as the turn card and ETA card. * <li><b>Prompts:</b> Prompts (e.g., incident alerts) may be triggered during Active Guidance * mode and can be added to the layout via {@link #onShowPrompt}. * </ul> * * This class caches its {@link ConstraintSet}s to ensure smooth transitions without needing to * recreate or inflate layouts continuously. */ public class StandardUiElementsLayoutDelegate extends NavigationLayoutDelegate { private final int layoutId; private final int buttonsContainerId; private ConstraintLayout layout; private AutoHidingVerticalLayout buttonsContainer; // We cache our ConstraintSet definitions to avoid cloning or rebuilding // constraint configurations programmatically on every transition. This optimization // keeps UI state switches (such as entering active guidance or popping up prompts) highly // performant. private ConstraintSet navigationReadyConstraintSet; private ConstraintSet activeGuidanceConstraintSet; private ConstraintSet activeGuidanceWithPromptConstraintSet; private ActiveGuidanceUiState activeGuidanceUiState; public StandardUiElementsLayoutDelegate() { layoutId = View.generateViewId(); buttonsContainerId = View.generateViewId(); } @Override public void onEnterNavigationReady( NavigationUiParent navigationUiParent, NavigationReadyUiState newState) { Context context = navigationUiParent.getViewContext(); // Implementation Tip: For simplicity, this sample instantiates views and constraints // programmatically. In a production application, you can safely inflate standard XML // layout templates to build your layout hierarchies and define base UI constraints. // Create the root layout if (layout == null) { layout = new ConstraintLayout(context); LayoutParams layoutParams = new LayoutParams(MATCH_PARENT, MATCH_PARENT); layout.setLayoutParams(layoutParams); layout.setId(layoutId); } // Add the Viewport (REQUIRED): // The viewport is an invisible bounding box used by Nav SDK to frame the vehicle // chevron and the upcoming route line. We want to position this view such that it avoids // being obscured by fully-opaque UI elements (like the turn card or the ETA card). removeFromParentView(newState.getViewport()); LayoutParams viewportLayoutParams = new LayoutParams(MATCH_PARENT, MATCH_PARENT); layout.addView(newState.getViewport(), viewportLayoutParams); // Add the Google Logo / Re-center Button (REQUIRED): // This view displays the Google logo during guidance and may transition into a // "Re-center" button if the user scrolls away from the vehicle chevron. It must // be added to the view hierarchy in all states. removeFromParentView(newState.getGoogleLogo()); LayoutParams googleLogoLayoutParams = new LayoutParams(MATCH_PARENT, WRAP_CONTENT); layout.addView(newState.getGoogleLogo(), googleLogoLayoutParams); // Add the container for UI buttons if (buttonsContainer == null) { // We use AutoHidingVerticalLayout to create an adaptive vertical button container that // automatically hides or shows child views based on available screen height. buttonsContainer = new AutoHidingVerticalLayout(context); buttonsContainer.setId(buttonsContainerId); } removeFromParentView(buttonsContainer); LayoutParams buttonsContainerLayoutParams = new LayoutParams(WRAP_CONTENT, MATCH_CONSTRAINT); layout.addView(buttonsContainer, buttonsContainerLayoutParams); // Add UI buttons to the container for (NavigationUiButton button : newState.getNavigationReadyButtons()) { removeFromParentView(button.getView()); buttonsContainer.addView(button.getView()); } // Build constraint set for Navigation Ready state if (navigationReadyConstraintSet == null) { navigationReadyConstraintSet = buildNavigationReadyConstraintSet(newState); } // Apply the constraints navigationReadyConstraintSet.applyTo(layout); // Set the layout in NavigationUiParent navigationUiParent.removeNavigationLayout(layout); navigationUiParent.setNavigationLayout(layout); } private ConstraintSet buildNavigationReadyConstraintSet(NavigationReadyUiState uiState) { ConstraintSet constraintSet = new ConstraintSet(); constraintSet.clone(layout); // Constrain viewport to the edges of its parent constraintSet.connect( uiState.getViewport().getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START); constraintSet.connect( uiState.getViewport().getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP); constraintSet.connect( uiState.getViewport().getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END); constraintSet.connect( uiState.getViewport().getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM); // Constrain the logo to the bottom start corner constraintSet.connect( uiState.getGoogleLogo().getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM); constraintSet.connect( uiState.getGoogleLogo().getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START); constrainButtonsToBottomEnd(constraintSet); return constraintSet; } @Override public void onLeaveNavigationReady( NavigationUiParent navigationUiParent, NavigationReadyUiState oldState) { buttonsContainer.removeAllViews(); layout.removeAllViews(); navigationUiParent.removeNavigationLayout(layout); } @Override public void onEnterActiveGuidance( NavigationUiParent navigationUiParent, NavigationReadyUiState oldState, ActiveGuidanceUiState newState) { activeGuidanceUiState = newState; Context context = navigationUiParent.getViewContext(); // Sizing Guideline: The turn card and ETA card are internally configured to adapt and size // themselves dynamically based on the layout width (non-wideMode vs. wideMode). Forcing fixed // widths or heights on these elements via layouts is unsupported. Always use WRAP_CONTENT to // let the elements determine their optimal proportions. // Add the turn card removeFromParentView(newState.getTurnCard()); LayoutParams turnCardLayoutParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT); layout.addView(newState.getTurnCard(), turnCardLayoutParams); // Add the ETA card removeFromParentView(newState.getEtaCard()); LayoutParams etaCardLayoutParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT); layout.addView(newState.getEtaCard(), etaCardLayoutParams); // Remove the Navigation Ready UI buttons for (NavigationUiButton button : oldState.getNavigationReadyButtons()) { removeFromParentView(button.getView()); } // By adding all buttons to the AutoHidingVerticalLayout, we can easily incorporate the latest // set of buttons when upgrading without any code changes required for (NavigationUiButton button : newState.getActiveGuidanceButtons()) { AutoHidingVerticalLayout.LayoutParams buttonLayoutParams = new AutoHidingVerticalLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); // Mark critical buttons (such as the compass) as high priority so they are the last to be // hidden by AutoHidingVerticalLayout when layout space is limited. if (button.getType() == COMPASS) { buttonLayoutParams.isHighPriority = true; } removeFromParentView(button.getView()); buttonsContainer.addView(button.getView(), buttonLayoutParams); } // Build constraint set for Active Guidance state if (activeGuidanceConstraintSet == null) { activeGuidanceConstraintSet = buildActiveGuidanceConstraintSet(context, newState); } // Apply the constraints activeGuidanceConstraintSet.applyTo(layout); } @Override public void onLeaveActiveGuidance( NavigationUiParent navigationUiParent, ActiveGuidanceUiState oldState, NavigationReadyUiState newState) { // Remove Active Guidance UI elements removeFromParentView(oldState.getEtaCard()); removeFromParentView(oldState.getTurnCard()); buttonsContainer.removeAllViews(); // Add Navigation Ready UI buttons for (NavigationUiButton button : newState.getNavigationReadyButtons()) { LayoutParams buttonLayoutParams = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT); buttonsContainer.addView(button.getView(), buttonLayoutParams); } navigationReadyConstraintSet.applyTo(layout); } private ConstraintSet buildActiveGuidanceConstraintSet( Context context, ActiveGuidanceUiState uiState) { ConstraintSet constraintSet = new ConstraintSet(); constraintSet.clone(layout); // Constrain turn card to top start corner constraintSet.connect( uiState.getTurnCard().getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP); constraintSet.connect( uiState.getTurnCard().getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START); // Constrain viewport to top of ETA card constraintSet.clear(uiState.getViewport().getId()); constraintSet.connect( uiState.getViewport().getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START); constraintSet.connect( uiState.getViewport().getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP); // Instead of constraining the viewport's top directly to the bottom of the turn card // (which varies in height and would trigger jumpy camera framing updates), we use a fixed // nominal height to estimate the height of the turncard. constraintSet.setMargin( uiState.getViewport().getId(), ConstraintSet.TOP, dpToPx(StyleValues.headerNominalHeightDp(), context)); constraintSet.connect( uiState.getViewport().getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END); constraintSet.connect( uiState.getViewport().getId(), ConstraintSet.BOTTOM, uiState.getEtaCard().getId(), ConstraintSet.TOP); constraintSet.clear(uiState.getGoogleLogo().getId(), ConstraintSet.BOTTOM); constrainLogoToTopOfEtaCard(uiState, constraintSet); constrainEtaCardToBottomStart(uiState, constraintSet); constrainButtonsToTopOfEtaCard(context, uiState, constraintSet); return constraintSet; } private static void constrainEtaCardToBottomStart( ActiveGuidanceUiState uiState, ConstraintSet constraintSet) { constraintSet.connect( uiState.getEtaCard().getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START); constraintSet.connect( uiState.getEtaCard().getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM); } private static void constrainLogoToTopOfEtaCard( ActiveGuidanceUiState uiState, ConstraintSet constraintSet) { constraintSet.connect( uiState.getGoogleLogo().getId(), ConstraintSet.BOTTOM, uiState.getEtaCard().getId(), ConstraintSet.TOP); } private void constrainButtonsToBottomEnd(ConstraintSet constraintSet) { constraintSet.clear(buttonsContainerId, ConstraintSet.BOTTOM); constraintSet.clear(buttonsContainerId, ConstraintSet.TOP); constraintSet.connect( buttonsContainerId, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP); constraintSet.connect( buttonsContainerId, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM); constraintSet.connect( buttonsContainerId, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END); } private void constrainButtonsToTopOfEtaCard( Context context, ActiveGuidanceUiState uiState, ConstraintSet constraintSet) { constraintSet.clear(buttonsContainerId, ConstraintSet.BOTTOM); constraintSet.clear(buttonsContainerId, ConstraintSet.TOP); constraintSet.connect( buttonsContainerId, ConstraintSet.BOTTOM, uiState.getEtaCard().getId(), ConstraintSet.TOP); constraintSet.connect( buttonsContainerId, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP); constraintSet.connect( buttonsContainerId, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END); constraintSet.setMargin( buttonsContainerId, ConstraintSet.TOP, dpToPx(StyleValues.headerNominalHeightDp(), context)); } @Override public void onShowPrompt(NavigationUiParent navigationUiParent, View newPrompt) { Context context = navigationUiParent.getViewContext(); layout.addView(newPrompt); // When a prompt is displayed at the bottom of the screen, we update our active constraints so // that the invisible Viewport sits entirely above the prompt. This automatically forces the // Nav SDK camera to adjust its zoom and framing so that the route chevron is always visible to // the driver. activeGuidanceWithPromptConstraintSet = buildActiveGuidanceWithPromptConstraintSet(context, newPrompt); activeGuidanceWithPromptConstraintSet.applyTo(layout); } @Override public void onChangePrompt( NavigationUiParent navigationUiParent, View oldPrompt, View newPrompt) { Context context = navigationUiParent.getViewContext(); activeGuidanceWithPromptConstraintSet.clear(oldPrompt.getId()); layout.removeView(oldPrompt); layout.addView(newPrompt); // When a prompt is displayed at the bottom of the screen, we update our active constraints so // that the invisible Viewport sits entirely above the prompt. This automatically forces the // Nav SDK camera to adjust its zoom and framing so that the route chevron is always visible to // the driver. activeGuidanceWithPromptConstraintSet = buildActiveGuidanceWithPromptConstraintSet(context, newPrompt); activeGuidanceWithPromptConstraintSet.applyTo(layout); } @Override public void onHidePrompt(NavigationUiParent navigationUiParent, View oldPrompt) { activeGuidanceWithPromptConstraintSet.clear(oldPrompt.getId()); layout.removeView(oldPrompt); activeGuidanceConstraintSet.applyTo(layout); } private ConstraintSet buildActiveGuidanceWithPromptConstraintSet(Context context, View prompt) { ConstraintSet constraintSet = new ConstraintSet(); constraintSet.clone(layout); // Constrain viewport to top of prompt constraintSet.clear(activeGuidanceUiState.getViewport().getId()); constraintSet.connect( activeGuidanceUiState.getViewport().getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START); constraintSet.connect( activeGuidanceUiState.getViewport().getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP); constraintSet.setMargin( activeGuidanceUiState.getViewport().getId(), ConstraintSet.TOP, dpToPx(StyleValues.headerNominalHeightDp(), context)); constraintSet.connect( activeGuidanceUiState.getViewport().getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END); constraintSet.connect( activeGuidanceUiState.getViewport().getId(), ConstraintSet.BOTTOM, prompt.getId(), ConstraintSet.TOP); // Constrain prompt to bottom start corner constraintSet.connect( prompt.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START); constraintSet.connect( prompt.getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM); return constraintSet; } private void removeFromParentView(View view) { if (view != null && view.getParent() != null) { ((ViewGroup) view.getParent()).removeView(view); } } private static int dpToPx(int dp, Context context) { return (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()); } }
完全なサンプルコードを表示する場合や、その他のレイアウト デリゲートの実装を確認する場合は、GitHub のレイアウト デリゲートのサンプルをご覧ください。この例の個々のソースファイルは、GitHub で確認することもできます。