Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppCompatActivity vs AppCompatDelegate

Recently I discovered what is AppCompatDelegate so a natural question arises - is it worse than using AppCompatActivity or do they have their differences and what are they?

like image 914
Necroqubus Avatar asked Jul 04 '17 02:07

Necroqubus


People also ask

What is AppCompatActivity?

AppCompatActivity(int contentLayoutId) Alternate constructor that can be used to provide a default layout that will be inflated as part of super. onCreate(savedInstanceState) .

What is AppCompatDelegate?

androidx.appcompat.app.AppCompatDelegate. This class represents a delegate which you can use to extend AppCompat's support to any Activity . When using an AppCompatDelegate , you should call the following methods instead of the Activity method of the same name: addContentView(android. view.

Should I use AppCompatActivity?

At the time of this writing (check the link to confirm it is still true), the Android Documentation recommends using AppCompatActivity if you are using an App Bar. This is the rational given: Beginning with Android 3.0 (API level 11), all activities that use the default theme have an ActionBar as an app bar.


1 Answers

If your activity class is not extending AppCompatActivity but you still want to use some of its features then you can you AppCompatDelegate.

You can create Appcompatdelegate with following lines of code in your activity class:

private AppCompatDelegate getDelegate() {
    if (mDelegate == null) {
       mDelegate = AppCompatDelegate.create(this, null);
    }
    return mDelegate;
}

Here is the example if you want to add Toolbar in your activity but your class is not extending AppCompatActivity.

https://medium.com/google-developer-experts/how-to-add-toolbar-to-an-activity-which-doesn-t-extend-appcompatactivity-a07c026717b3

like image 111
Ani Avatar answered Oct 12 '22 02:10

Ani