Why should I use AppCompatActivity instead of a st

2019-06-27 20:52发布

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)

2条回答
叛逆
2楼-- · 2019-06-27 20:59

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.

查看更多
3楼-- · 2019-06-27 20:59

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.

查看更多
登录 后发表回答