Is setSupportActionbar required anymore?

眉间皱痕 提交于 2021-02-04 05:52:27

问题


With the new Toolbar widget introduced and it's AppCompat (android.support.v7.widget.Toolbar) version available, is it required to call setSupportActionbar(toolbar) anymore? Or is there any advantage of calling setSupportActionbar; as now we can set title, sub-title, navigation-icon, navigation-icon-click-listener (getSupportActionBar().setDisplayHomeAsUpEnabled(true) replacement), menu, menu-click-listener (options-menu replacement) etc directly on the toolbar without ever calling setSupportActionbar.


回答1:


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.



来源:https://stackoverflow.com/questions/33687837/is-setsupportactionbar-required-anymore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!