- ToolBar menu item click in a fragment (Kotlin)
- ToolBar menu item click in a fragment (Kotlin)
- Android kotlin: How to change app bar/toolbar for one fragment in an activity?
- How to implement toolbar with viewbinding in fragment?
- Android Toolbar Tutorial — XML Layout and Kotlin
- What is Android Toolbar?
- Toolbar Gradle Dependencies
- Android Apps Default Toolbar
- Toolbar from Themes
- Toolbar XML Layout
- 1. Setting Toolbar Background Color
- 2. Setting the Theme
- 3. Setting title, subtitle, icons
- 4. Toolbar Preview
- Android Toolbar Themes
- Android Custom Toolbar
- Creating Toolbar using Kotlin Code
ToolBar menu item click in a fragment (Kotlin)
I’ve came to the conclusion (maybe I’m wrong) that you can’t manage ActionBars from kotlin fragments, that’s why you have to use toolbars. My goal is to have two buttons in toolbar to have possibility to back to previous fragment + onClickSecondButton make some action.
ToolBar menu item click in a fragment (Kotlin)
In my app, i have an Activity, which has a FrameLayout in it. In this FrameLayout, there is a fragment, containing a ToolBar and a RecyclerView.
In this toolbar, i have a search button, which should start an Activity on item click. However, when i try to use onOptionsItemSelected, the apps gets built and installed succesfully, but when i try to tap that button in question, nothing happens. The Logcat, doesnt say anything either.
Can some points me what im doing wrong? Are there simpler or other easy ways to manage on ToolBar item clicks?
class FragmentTrack : Fragment() < . override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setHasOptionsMenu(true) >override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(R.layout.fragment_track, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) < super.onViewCreated(view, savedInstanceState) . topToolbar.setNavigationOnClickListener < val dialog = FragmentBottomSheetDrawer() dialog.show(childFragmentManager, dialog.tag) >> override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) < inflater.inflate(R.menu.menu_toolbar, menu) super.onCreateOptionsMenu(menu, inflater) >override fun onOptionsItemSelected(item: MenuItem): Boolean < when(item.itemId) < R.id.fsvSearch ->Toast.makeText(context, "Clicked search button", Toast.LENGTH_SHORT).show() > return true > >
I found a solution thanks to some external help. Its possible to work on the Toolbars item in an easier way.
In the onViewCreated method, we must add:
topToolbar.inflateMenu(R.menu.menu_toolbar) topToolbar.setOnMenuItemClickListener < when(it.itemId) < R.id.fsvSearch ->//your code > true >
Also, if the menu gets duplicated, remove the app:menu tag in the Toolbars xml
thanks Meltix for this, I’ve done a lot of research but most of the posts in SO are about Java and old fashioned ActionBar. There is not much info about material ToolBar and kotlin examples. In my case I’m working on an old app developed mostly in Java but now developing new functionalities in Kotlin. In my fragment, I wasn’t able to change the ActionBar’s icons and behaviour (I wanted a particular ActionBar for my fragment). The solution I found is to hide the ActionBar and create a Toolbar inflating a custom menu inside. Also I added a back arrow button (thanks to John: here). I’ve came to the conclusion (maybe I’m wrong) that you can’t manage ActionBars from kotlin fragments, that’s why you have to use toolbars. Here is my code in case it can help someone.
MyFragment.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?) < // hide the old actionBar (activity as AppCompatActivity).supportActionBar. hide() // create the toolbar val toolbar = binding?.myToolbar // add the back arrow button, see function below val resId = getResIdFromAttribute(toolbar.context, android.R.attr.homeAsUpIndicator) toolbar.navigationIcon = ContextCompat.getDrawable(toolbar.context, resId) // tapping on the arrow will pop the current fragment toolbar.setNavigationOnClickListener < parentFragmentManager?.popBackStackImmediate() >// change toolbar title toolbar.title = "Some title" // inflate a custom menu, see code below toolbar.inflateMenu(R.menu.my_custom_menu) toolbar.setOnMenuItemClickListener < when (it.itemId) < R.id.infoButton ->someAction() > true > > // get back arrow icon @AnyRes fun getResIdFromAttribute(context: Context, @AttrRes attr: Int): Int
my_fragment.xml
my_custom_menu.xml
Learn Jetpack Navigation, subject Last updated Jan 10, 2022. account_circle Written by Android Developer Relations. 1. Before you begin. The Navigation Architecture Component simplifies implementing navigation, while also helping you visualize your app’s navigation flow. The library provides a number of benefits, including: …
Android kotlin: How to change app bar/toolbar for one fragment in an activity?
In my android app I have 4 fragments in my main activity where I can swipe left and right to access them.
Right now, each fragment has the same app bar as laid out in my activity_main.xml:
However, I would like to change the app bar for one of the fragments (the home fragment) to have a centered logo and a taller height.
This is my MainActivity.kt where the app bar/nav controller/fragments are configured:
@AndroidEntryPoint class MainActivity : AppCompatActivity() < lateinit var user: ImageButton lateinit var toolbar: Toolbar lateinit var bottomNavigationView: BottomNavigationView lateinit var loginViewModel: LoginViewModel lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) val binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) loginViewModel = ViewModelProvider(this).get(LoginViewModel::class.java) toolbar = binding.toolbar bottomNavigationView = binding.bottomNavigation user = binding.userButton setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) Fresco.initialize(this) val navHostFragment = supportFragmentManager.findFragmentById(R.id.mainNavigationFragment) as NavHostFragment navController = navHostFragment.navController bottomNavigationView.setupWithNavController(navController) // Set up tool bar with navController and appBarConfiguration val appBarConfiguration = AppBarConfiguration( setOf( R.id.homeFragment, R.id.mapFragment, R.id.resourcesFragment, R.id.moreFragment ) ) toolbar.setupWithNavController(navController, appBarConfiguration) // Show navigation bar and user bottom on top level fragments navController.addOnDestinationChangedListener < _, destination, _ ->when (destination.id) < R.id.homeFragment, R.id.mapFragment, R.id.resourcesFragment, R.id.moreFragment -> < bottomNavigationView.visibility = View.VISIBLE user.visibility = View.VISIBLE >else -> < bottomNavigationView.visibility = View.GONE user.visibility = View.GONE >> > user.setOnClickListener < loginViewModel.loadAccount(this@MainActivity, binding.root) < navController.navigate(R.id.userFragment) >> > override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) < super.onActivityResult(requestCode, resultCode, data) if (requestCode == 1) < user.callOnClick() >> >
In my HomeFragment.kt onCreateView, where I would like to change the app bar/toolbar, I added the following line of code:
(activity as MainActivity?). supportActionBar. setLogo(R.drawable.logo_mt)
This successfully placed my logo in the center, but it changed every fragments app bar and not just the home fragment. I would also like to be able to edit the logos size and the toolbars size.
Set theme to NoActionBar and then set custom toolbar in AppBarLayout in each fragment as per your need
The typical recommendation is to remove the toolbar from the Activity , and add one in each Fragment ‘s layout instead. That way you can configure each one however you like (even if most of them are identical). If you’re doing a single-activity app, you might run into a «I don’t always need a toolbar» situation, and if it’s a shared activity, it can’t have things that aren’t shared across all components.
Just bear in mind if you go this way, the setUpWithNavController call sets the title on your toolbar using any label values set on destinations in your nav graph. And when you navigate to another fragment, that title may change to the new destination a split second before the fragment changes. Not a problem if the destination has a toolbar and the title is in the same place — but you might see a glitch if one is centred, because it’ll be obvious if the title changes early
Another thing you could try (haven’t done it myself but it’s an idea) is having the activity manage the toolbar — height, centering etc. When a fragment attaches, it could inform the activity what it needs the toolbar to look like. You could just have an interface on the parent activity, or have a ViewModel with some ToolbarConfig value that it observes, and that the fragment sets, that kind of thing. Might want to look into using a CoordinatorLayout to make it grow and shrink all fancy-like
This is what I did with a seamless slide between fragments. I can put any button on any toolbar and resize them. You can see both toolbars simultaneously as it slides back and forth and easily respond to the movements. I should sign up for Git to post a sample as it would probably be easier to see it in action.
is on what looks like the Activity main toolbar but it’s not. The TouchTargetSizeCheck is not material as the buttons turn out at 48×48. This button is in the first fragment file called fragment_first.xml that runs a constraint layout:
And the toolbar can easily resize and have any text title:
I think I am going to implement this for future apps because I can’t find official documentation otherwise.
Android — Access Toolbar (and its children) from, If you implement toolbar views (spinners, Buttons..) in the main activity, the fragments that will be replaced in this activity can see toolbar and interact with its views. else if, you need to handle actions depending on this views, you can use: getActivity.findViewById(); inside fragment.
How to implement toolbar with viewbinding in fragment?
I would like to implement a toolbar in the fragment. I am using binding to use elements from .xml. I implement in Kotlin, android studio.
I have seen: Unable to show toolbar while using DataBinding in android and many other articles, documentation as well, but everywhere I cannot find the proper implementation with binding.
Here I have tried many different implementations. The main issue is when I make it with documentation and instead of define toolbar using findById I define it by binding.toolbar where misstype appears where it wants toolbar? not binding toolbar.
override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? < // doesn't work setConentView and setSupportACtionBar on Red binding = FragmentItemSecondBinding.setContentView(this, R.layout.fragment_item_second) setSupportActionBar(binding.toolbar) binding.setProduct(product); binding = FragmentItemSecondBinding.inflate(layoutInflater) return binding.root >
In documentation and other videos it should work when I make code like below, but setsupportactionbar doesn’t exist.
val toolbar = binding.toolbar setSupportActionBar(toolbar)
What is difference between:
I use the first one. My goal is to have two buttons in toolbar to have possibility to back to previous fragment + onClickSecondButton make some action.
If you import external layout using tag, you need to set its own binding, as well. Change your code by;
private lateinit binding: FragmentItemSecondBinding private lateinit toolbarBinding: ToolbarBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? < binding = FragmentItemSecondBinding.inflate(inflater, container, false) toolbarBinding = ToolbarBinding.bind(binding.toolbar) (requireActivity() as YourActivity).setSupportActionBar(toolbarBinding.toolbar) // in toolbar.xml set an ID to your component e.g. toolbar binding.setProduct(product); return binding.root >
Of course, I tried to keep code as short as possible. You should make your bindings nullable and dispose them in onDestroyView to avoid memory leaks.
Android — Calling setSupportActionBar in a fragment, Add a comment. 1. The AppCompatActivity documentation states that getSupportActionBar () is an instance method. By doing AppCompatActivity ().setSupportActionBar (toolbar) you are calling the constructor without assigning the reference to a variable and then expecting that instance to call the method, …
Android Toolbar Tutorial — XML Layout and Kotlin
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Android Toolbar widget is used to create menus in the apps. We will learn how to create a Toolbar using the XML layout and Kotlin code. We will implement various toolbar properties in an example Android app.
What is Android Toolbar?
Android Toolbar widget is generally found on the top of the screen. The application title, logo, navigation icon, and the menu bar is displayed inside the toolbar. The toolbar is the material design replacement for the old and now deprecated ActionBar.
Toolbar Gradle Dependencies
implementation 'com.android.support:appcompat-v7:27.1.0'
Android Apps Default Toolbar
When you create a new android studio project, you might see that the activity_main.xml doesn’t have any Toolbar defined in the XML. Still, when you see the XML preview, there is a Toolbar with the application name by default at the top. This is because the following style is defined in the styles.xml, which is ultimately attached in the AndroidManifest.xml file.
Toolbar from Themes
DarkActionBar theme adds the Toolbar at the top of the app by default. We can change the parent theme in the above image from Theme.AppCompat.Light.DarkActionBar to Theme.AppCompat.Light.NoActionBar to remove the Toolbar that is displayed as a part of the activity theme. Let’s change the theme and add the Toolbar in the activity_main.xml file.
Toolbar XML Layout
This will display a Transparent Toolbar with no text or any other items. We have to add more properties to utilize Toolbar effectively.
1. Setting Toolbar Background Color
android:background="@color/colorPrimary"
2. Setting the Theme
android:theme="@style/ThemeOverlay.AppCompat.Dark"
We are using a default theme for the layout. Dark indicates that the text colors would be light (generally white). We can also create our own custom themes in the styles.xml file.
3. Setting title, subtitle, icons
- Title: app:title=»Androidly Toolbar»
- Subtitle: app:subtitle=»Sub»
- Logo: app:logo=»@android:drawable/ic_menu_call»
- Navigation Icon: app:navigationIcon=»@drawable/ic_menu_black_24dp»
4. Toolbar Preview
Our toolbar looks like the below image after doing all the above changes.
Toggle the theme to @style/ThemeOverlay.AppCompat.Light and you shall see inverted colors.
There are many XML attributes to customize the Toolbar properties. For example: titleTextColor, subtitleTextColor, subtitleTextAppearance, titleTextAppearance, etc.
Android Toolbar Themes
We can create our own custom styles and assign them as a theme on our Toolbar. This will be much easier than adding all those XML properties.
Let’s use the custom theme in the activity_main.xml file.
The AppTheme style gets updated in the AndroidManifest.xml file. Our Toolbar will look like the below image.
Android Custom Toolbar
We can define our own custom views inside a Toolbar. The following layout defines custom views within the toolbar.
Output:
Creating Toolbar using Kotlin Code
We can create toolbars programmatically using Kotlin code. Each of the toolbar XML properties has its equivalent Kotlin methods. The following MainActivity.kt class is defined below.
package net.androidly.androidlytoolbar import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.widget.Toolbar import android.widget.Toast class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar = findViewById(R.id.toolbar) as Toolbar? setSupportActionBar(toolbar) toolbar?.title = "Androidly" toolbar?.subtitle = "Sub" toolbar?.navigationIcon = ContextCompat.getDrawable(this,R.drawable.ic_menu_black_24dp) toolbar?.setNavigationOnClickListener < Toast.makeText(applicationContext,"Navigation icon was clicked",Toast.LENGTH_SHORT).show() >> >
Using the as operator, we safely typecast the XML view to the toolbar instance. The setNavigationOnClickListener triggers a toast message when the navigation icon is clicked from the menu.
You can download the Toolbar project from the following link: AndroidlyToolbar
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.