Set Subtitle of Toolbar with JetPack Navigation Architecture Components - android

I'm using the JetPack Navigation Architecture Components and I can set the title of the Toolbar in my Navigation Graph with android:label="#string/event_lists_toolbar_title". I would also like to set the subtitle, but cannot find a way to do so, except via code in my Fragment:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as? AppCompatActivity)?.supportActionBar?.subtitle = getString(R.string.my_subtitle)
// ...
}
But the subtitle then stays and I have to reset it after I navigate again to another Screen. I could do this in the onPause() function or like this in my Activity (NavController.OnDestinationChangedListener):
override fun onDestinationChanged(controller: NavController, destination: NavDestination, arguments: Bundle?) {
// resets subtitle of Toolbar
if (destination.id != R.id.fragment_with_subtitle) {
supportActionBar?.subtitle = ""
}
}
Isn't there a better solution for this? Doesn't support Navigation that out of the box?

Related

Jetpack compose deeplink handling branch.io

I'm using branch.io for handling deep links. Deep links can contain custom metadata in a form of JsonObject. The data can be obtained by setting up a listener, inside MainActivity#onStart() which is triggered when a link is clicked.
override fun onStart() {
super.onStart()
Branch
.sessionBuilder(this)
.withCallback { referringParams, error ->
if (error == null) {
val eventId = referringParams?.getString("id")
//Here I would like to navigate user to event screen
} else {
Timber.e(error.message)
}
}
.withData(this.intent?.data).init()
}
When I retrieve eventId from referringParams I have to navigate the user to the specific event. When I was using Navigation components with fragments I could just do:
findNavController(R.id.navHost).navigate("path to event screen")
But with compose is different because I can't use navController outside of Composable since its located in MainActivity#onCreate()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
//I cant access navController outside of composable function
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = "HomeScreen",
) {
}
}
}
My question is, how can I navigate the user to a specific screen from MainActivity#onStart() when using jetpack compose navigation
rememberNavController has pretty simple implementation: it creates NavHostController with two navigators, needed by Compose, and makes sure it's restored on configuration change.
Here's how you can do the same in your activity, outside of composable scope:
private lateinit var navController: NavHostController
private val navControllerBundleKey = "navControllerBundleKey"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
navController = NavHostController(this).apply {
navigatorProvider.addNavigator(ComposeNavigator())
navigatorProvider.addNavigator(DialogNavigator())
}
savedInstanceState
?.getBundle(navControllerBundleKey)
?.apply(navController::restoreState)
setContent {
// pass navController to NavHost
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putBundle(navControllerBundleKey, navController.saveState())
super.onSaveInstanceState(outState)
}

How can i show another framents with bottom navigation view

My task now is have active bottom navigation view and toolbar which has buttons when first of buttons open new fragment and second which return to initial fragment.
i had base fragmentlayout and bottom navigation view. I found way change fragment without bottom navigation view with supportFragmentManager. But after replace() my bottom navigation view stops work. How can i fix this?
if you didnt understand i attach photos
tool bar buttons opens and returns fragments without bottom navigation view
Now my main activity look like
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
val navHostFragment = supportFragmentManager.findFragmentById(binding.fragmentContainerView.id)
as NavHostFragment
binding.bnvBase.setupWithNavController(navHostFragment.navController)
binding.toolbar.ivBack.setOnClickListener {
supportFragmentManager.commit {
replace(R.id.fragmentContainerView, PokemonCardsFragment())
setReorderingAllowed(true)
addToBackStack(null)
}
}
binding.toolbar.searchButton.setOnClickListener {
supportFragmentManager.commit {
replace(R.id.fragmentContainerView, SearchPokemonCardsFragment(
binding.toolbar.searchSrcText.text.toString()
))
setReorderingAllowed(true)
addToBackStack(null)
}
}
}

how to perform an action instead of moving to another destination if I click a menu in Navigation Drawer using Navigation Component?

I am trying to use Jetpack Navigation component. so navigation component will automatically handle if I want to segue from a destination to another destination when I click a menu in the navigation drawer
but I want to perform an action if a menu is clicked, say for example if a menu in drawer is clicked then I want to show a toast message.
in old way, ie using fragment transaction, I can easily check from onNavigationItemSelected, but I am no longer find that method
so how to do that in navigation component ?
I have tried to check onDestinationChanged , but it doesn't work
override fun onDestinationChanged(controller: NavController, destination: NavDestination, arguments: Bundle?) {
if (destination.id == R.id.my_destination {
// show toast in here
// but it doesn't work
}
}
here is my MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var navController : NavController
private lateinit var appBarConfiguration: AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
appBarConfiguration = AppBarConfiguration(setOf(
R.id.destination_share,
R.id.destination_message,
R.id.destination_chat),
drawer_layout
)
// init nav controller
navController = Navigation.findNavController(this,R.id.nav_host_fragment)
// set toolbar
setSupportActionBar(toolbar)
// set up navigation drawer
NavigationUI.setupActionBarWithNavController(this,navController, appBarConfiguration)
NavigationUI.setupWithNavController(navigation_view,navController)
}
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(navController,appBarConfiguration)
}
}
You can handle Menu clicks as following
navView.menu.findItem(R.id.logout)
.setOnMenuItemClickListener { menuItem: MenuItem? ->
// write your code here
true
}
Have you tried using
bottom_nav_view.setOnNavigationItemSelectedListener {
if (destination.id == R.id.my_destination {
// show toast in here
// but it doesn't work
}
}

Hide Bottom Navigation View in fragment

I want to hide bottomNavigationView in some fragments.
I have tried the below code, but it has a flicker effect. (bottomNavigationView hide before the nextFragment becomes visible.
val navController = this.findNavController(R.id.nav_host_home)
navController.addOnDestinationChangedListener { _, destination, _ ->
when (destination.id) {
R.id.searchArticlesFragment -> bnvMain.visibility = View.GONE
R.id.articleFragment -> bnvMain.visibility = View.GONE
else -> bnvMain.visibility = View.VISIBLE
}
}
I have also tried another code. But it resizes the fragment. And giving OutOfMemoryException in Destination Fragment.
supportFragmentManager.registerFragmentLifecycleCallbacks(object :
FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentViewCreated(
fm: FragmentManager,
f: Fragment,
v: View,
savedInstanceState: Bundle?
) {
when (f) {
is SearchArticlesFragment -> bnvMain.visibility = View.GONE
is ArticleDetailsFragment -> bnvMain.visibility = View.GONE
else -> bnvMain.visibility = View.VISIBLE
}
}
}, true)
Please help me how can I hide the bottomNavigationView in the proper and best possible way? Is this the only way I can hide the bottomNavigationView? How youtube and Instagram achieve this behavior?
If your code follows single activity design pattern then the following solution suites you.
Create a method inside the parent activity to hide/show bottomNavigationView.
Create a BaseFragment class(create your fragments by extending this BaseFragment Class)
In the BaseFragment create a variable to hold the bottomNavigationViewVisibility (hide/show)
In onActivityCreated method of the BaseFragment, get the activity reference and set the bottomNavigationViewVisibility by calling the method which we created in STEP1.
In each fragment you create, just set the bottomNavigationViewVisibility variable.
Example:
In parentAcitivty layout, file add bottomNavigationView
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/main_bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:labelVisibilityMode="labeled"
app:menu="#menu/main_nav" />
Step 1: In parent activity, create a method to change the visibility.
fun setBottomNavigationVisibility(visibility: Int) {
// get the reference of the bottomNavigationView and set the visibility.
activityMainBinding.mainBottomNavigationView.visibility = visibility
}
Step 2 & 3 & 4:
abstract class BaseFragment : Fragment() {
protected open var bottomNavigationViewVisibility = View.VISIBLE
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// get the reference of the parent activity and call the setBottomNavigationVisibility method.
if (activity is MainActivity) {
var mainActivity = activity as MainActivity
mainActivity.setBottomNavigationVisibility(bottomNavigationViewVisibility)
}
}
override fun onResume() {
super.onResume()
if (activity is MainActivity) {
mainActivity.setBottomNavigationVisibility(bottomNavigationViewVisibility)
}
}
}
Step 5:
class SampleFragment1 : BaseFragment() {
// set the visibility here, it takes care of setting the bottomNavigationView.
override var navigationVisibility = View.VISIBLE
// override var navigationVisibility = View.GONE
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sampleFragment1, container, false)
}
}

Hide android bottom navigation view for child screens/ fragments

I'm trying to create a single activity Android application.
I have MainActivity (only activity) with BottomNavigationView, three top level fragments and some child fragments. My requirement is whenever the screen is showing top level fragments, bottom navigation should be visible such that switching is possible. But when I'm viewing any of the child fragments, bottom navigation should be hidden.
Is there any out-of-box way using the Navigation component or need to change the visibility manually ?
Update (Navigation component 1.0)
As of Navigation component 1.0.0-alpha08, method addOnNavigatedListener(controller: NavController, destination: NavDestination) was changed to addOnDestinationChangedListener(controller: NavController, destination: NavDestination, arguments: Bundle). Its behavior was also slightly changed (it is also called if the destinations arguments change).
Old Answer
You can use NavController.OnNavigatedListener to achieve this behavior (set it in Activity onCreate):
findNavController(R.id.container).addOnNavigatedListener { _, destination ->
when (destination.id) {
R.id.dashboardFragment -> showBottomNavigation()
else -> hideBottomNavigation()
}
}
private fun hideBottomNavigation() {
// bottom_navigation is BottomNavigationView
with(bottom_navigation) {
if (visibility == View.VISIBLE && alpha == 1f) {
animate()
.alpha(0f)
.withEndAction { visibility = View.GONE }
.duration = EXIT_DURATION
}
}
}
private fun showBottomNavigation() {
// bottom_navigation is BottomNavigationView
with(bottom_navigation) {
visibility = View.VISIBLE
animate()
.alpha(1f)
.duration = ENTER_DURATION
}
}
Using addOnDestinationChangedListener works, and it's the solution recommended in the official documentation, but it does cause some flickering, as the callback is executed before the fragment is attached.
I find the below answer more flexible, and handles animations better:
supportFragmentManager.registerFragmentLifecycleCallbacks(object : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentViewCreated(fm: FragmentManager, f: Fragment, v: View, savedInstanceState: Bundle?) {
TransitionManager.beginDelayedTransition(binding.root, Slide(Gravity.BOTTOM).excludeTarget(R.id.nav_host_fragment, true))
when (f) {
is ModalFragment -> {
binding.bottomNavigation.visibility = View.GONE
}
else -> {
binding.bottomNavigation.visibility = View.VISIBLE
}
}
}
}, true)
You can customize it depending on the transitions between your fragments, by choosing different animation (on my example it's a Slide), or by making the call at another lifecycle callback.
You have to make a method in MainActivity for visibility. Do call that method from fragments where you want to show or hide.
One thing I faced with such scenario is, bottom navigation visibility is not being properly gone. So I put bottom navigation view in Relative layout and hide that parent view.
you just need to write this code in MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Getting the Navigation Controller
navController = Navigation.findNavController(this, R.id.fragment)
//Setting the navigation controller to Bottom Nav
bottomNav.setupWithNavController(navController)
//Setting up the action bar
NavigationUI.setupActionBarWithNavController(this, navController)
//setting the Bottom navigation visibiliy
navController.addOnDestinationChangedListener { _, destination, _ ->
if(destination.id == R.id.full_screen_destination ){
bottomNav.visibility = View.GONE
}else{
bottomNav.visibility = View.VISIBLE
}
}
}
get more details from the android developer documentation:
Update UI components with NavigationUI
So even tho this question was already answered and the accepted answer is one that works, here is the code to actually achieve this behaviour:
MainActivity
fun hideBottomNav() {
bottomNavigationView.visibility = View.GONE
}
fun showBottomNav() {
bottomNavigationView.visibility = View.VISIBLE
}
Then you call the functions in your fragment onViewCreated(), onDetach() function, like:
Fragment
class FragmentWithOutBottomNav() : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as MainActivity).hideBottomNav()
}
override fun onDetach() {
super.onDetach()
(activity as MainActivity).showBottomNav()
}
}
Hope I could help some people. Happy coding!
navController.addOnDestinationChangedListener { _, destination, _ ->
val isMainPage = bottomNavigationView.selectedItemId == destination.id
bottomNavigationView.isVisible = isMainPage
}

Categories

Resources