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 package androidx.navigation.ui 17 18 import android.graphics.drawable.Drawable 19 import android.os.Bundle 20 import androidx.annotation.StringRes 21 import androidx.appcompat.widget.Toolbar 22 import androidx.navigation.NavController 23 import androidx.navigation.NavDestination 24 import androidx.transition.TransitionManager 25 import com.google.android.material.appbar.CollapsingToolbarLayout 26 import java.lang.ref.WeakReference 27 28 /** 29 * The OnDestinationChangedListener specifically for keeping a CollapsingToolbarLayout+Toolbar 30 * updated. This handles both updating the title and updating the Up Indicator, transitioning 31 * between the drawer icon and up arrow as needed. 32 */ 33 internal class CollapsingToolbarOnDestinationChangedListener( 34 collapsingToolbarLayout: CollapsingToolbarLayout, 35 toolbar: Toolbar, 36 configuration: AppBarConfiguration 37 ) : AbstractAppBarOnDestinationChangedListener(collapsingToolbarLayout.context, configuration) { 38 39 private val mCollapsingToolbarLayoutWeakReference: WeakReference<CollapsingToolbarLayout> = 40 WeakReference(collapsingToolbarLayout) 41 private val mToolbarWeakReference: WeakReference<Toolbar> = WeakReference(toolbar) 42 onDestinationChangednull43 override fun onDestinationChanged( 44 controller: NavController, 45 destination: NavDestination, 46 arguments: Bundle? 47 ) { 48 val collapsingToolbarLayout = mCollapsingToolbarLayoutWeakReference.get() 49 val toolbar = mToolbarWeakReference.get() 50 if (collapsingToolbarLayout == null || toolbar == null) { 51 controller.removeOnDestinationChangedListener(this) 52 return 53 } 54 super.onDestinationChanged(controller, destination, arguments) 55 } 56 setTitlenull57 override fun setTitle(title: CharSequence?) { 58 val collapsingToolbarLayout = mCollapsingToolbarLayoutWeakReference.get() 59 if (collapsingToolbarLayout != null) { 60 collapsingToolbarLayout.title = title 61 } 62 } 63 setNavigationIconnull64 override fun setNavigationIcon(icon: Drawable?, @StringRes contentDescription: Int) { 65 val toolbar = mToolbarWeakReference.get() 66 if (toolbar != null) { 67 val useTransition = icon == null && toolbar.navigationIcon != null 68 toolbar.navigationIcon = icon 69 toolbar.setNavigationContentDescription(contentDescription) 70 if (useTransition) { 71 TransitionManager.beginDelayedTransition(toolbar) 72 } 73 } 74 } 75 } 76