Why should I use AppCompatActivity instead of a standalone Toolbar to create an Activity's app bar?

谁都会走 提交于 2019-12-10 17:18:22

问题


There are two principal ways of creating an app bar for an activity in API 21+ using the Toolbar.

  1. Create an activity which extends AppCompatActivity and then follow the instructions here

  2. Create a standalone Toolbarwhich acts as an app bar (define the Toolbar in xml using android.support.v7.widget.Toolbar) and then inflate a menu into it like this: ` toolbar.inflateMenu(R.menu.homeview_menu_common);

My question is: what are the benefits and drawbacks of doing one over the other?`

A related question to this topic can also be found here (How can an activity use a Toolbar without extending AppCompatActivity)


回答1:


Short answer: No you should make your activity extend AppCompatActivty

You can create a toolbar without AppCompatActivty but besides an app bar the AppCompat also brings with it the support libraries that allow you to add material design to your app going as far back as API level 7 of Android.

Unless there is a specific reason for not using AppCompat all your Activites should extend AppCompatActivty to model a Material app.




回答2:


You need to use an AppCompatActivity extended Activity because, when you set up the Toolbar as the ActionBar with setSupportActionBar(Toolbar) you get the ability to reference it through Context.getSupportActionBar() from nearly anywhere in your code i.e Fragment. But, if you don't extend AppCompatActivity you can't easily get a reference to the Toolbar from anywhere else other than the Activity in which it was defined.



来源:https://stackoverflow.com/questions/33428651/why-should-i-use-appcompatactivity-instead-of-a-standalone-toolbar-to-create-an

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