However setSupportActionbar() method and ActionBar API remains the documented way of implementing an app bar, it looks rather as a way to use Toolbar with the familiar API that developers are used to. In reality ActionBar API only complicates things often, take a look at this article for an example.
Nowadays, when a single activity architecture and navigation component are recommended ways of implementing Android applications, it's very easy to setup a fragment toolbar using NavigationUI library, for example:
<!-- my_fragment.xml -->
<androidx.constraintlayout.widget.ConstraintLayout ...>
<com.google.android.material.appbar.MaterialToolbar
...
android:id="@+id/toolbar"
app:menu="@menu/my_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
class MyFragment : Fragment() {
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val navController = findNavController()
binding.toolbar.setupWithNavController(navController)
binding.toolbar.setOnMenuItemClickListener { ... }
}
}
It's really that simple, as a result you'll get a toolbar with an auto set title, working back button and options menu. Here you can find the full GitHub sample which demonstrates a minimal Toolbar setup using NavigationUI.
So, there's no advantages of using ActionBar API at all? Maybe I'm wrong, but the only situation I see it useful is a single app wide toolbar. In this case you can put a toolbar into your activity and setup it differently in each fragment, for example by overriding onCreateOptionsMenu()
. But by my experience toolbars tend to vary significantly between fragments so it's easier to have a separate toolbar for each fragment, the choice is discussed in this thread. You can also take a look at the navigation component documentation: Support app bar variations.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…