AppCompatDelegate


abstract class AppCompatDelegate


This class represents a delegate which you can use to extend AppCompat's support to any android.app.Activity.

When using an AppCompatDelegate, you should call the following methods instead of the android.app.Activity method of the same name:

The following methods should be called from the android.app.Activity method of the same name:

An Activity can only be linked with one AppCompatDelegate instance, therefore the instance returned from create should be retained until the Activity is destroyed.

Summary

Constants

const Int

Flag for specifying the behavior of action modes when an Action Bar is not present.

const Int

Flag for enabling the support Action Bar.

const Int

Flag for requesting an support Action Bar that overlays window content.

const Int

This property is deprecated.

Use MODE_NIGHT_AUTO_TIME instead

const Int

Night mode which uses a dark mode when the system's 'Battery Saver' feature is enabled, otherwise it uses a 'light mode'.

const Int

This property is deprecated.

Automatic switching of dark/light based on the current time is deprecated.

const Int

Mode which uses the system's night mode setting to determine if it is night or not.

const Int

Night mode which uses always uses a light mode, enabling notnight qualified resources regardless of the time.

const Int

An unspecified mode for night mode.

const Int

Night mode which uses always uses a dark mode, enabling night qualified resources regardless of the time.

Public functions

abstract Unit

Should be called instead of addContentView}

abstract Boolean

Applies the currently selected night mode to this delegate's host component.

Unit

This function is deprecated.

use attachBaseContext2 instead.

Context

Should be called from attachBaseContext.

java-static AppCompatDelegate
create(activity: Activity, callback: AppCompatCallback?)

Create an androidx.appcompat.app.AppCompatDelegate to use with activity.

java-static AppCompatDelegate
create(dialog: Dialog, callback: AppCompatCallback?)

Create an androidx.appcompat.app.AppCompatDelegate to use with dialog.

java-static AppCompatDelegate
create(context: Context, activity: Activity, callback: AppCompatCallback?)

Create an androidx.appcompat.app.AppCompatDelegate to use with a context and hosted by an Activity.

java-static AppCompatDelegate
create(context: Context, window: Window, callback: AppCompatCallback?)

Create an androidx.appcompat.app.AppCompatDelegate to use with a context and a window.

abstract View!
createView(parent: View?, name: String!, context: Context, attrs: AttributeSet)

This should be called from a LayoutInflater.Factory2 in order to return tint-aware widgets.

abstract T?
<T : View?> findViewById(id: @IdRes Int)

Finds a view that was identified by the id attribute from the XML that was processed in onCreate.

java-static LocaleListCompat

Returns application locales for the calling app as a LocaleListCompat.

Context?

Returns the context for the current delegate.

java-static Int

Returns the default night mode.

abstract ActionBarDrawerToggle.Delegate?

Returns an ActionBarDrawerToggle.Delegate which can be returned from your Activity if it implements ActionBarDrawerToggle.DelegateProvider.

Int

Returns the night mode previously set via getLocalNightMode.

abstract MenuInflater!

Return the value of this call from your getMenuInflater

abstract ActionBar?

Support library version of getActionBar.

abstract Boolean
hasWindowFeature(featureId: Int)

Query for the availability of a certain feature.

abstract Unit

Installs AppCompat's android.view.LayoutInflater Factory so that it can replace the framework widgets with compatible tinted versions.

abstract Unit

Should be called from invalidateOptionsMenu} or supportInvalidateOptionsMenu.

java-static Boolean

Returns whether vector drawables on older platforms (< API 21) can be accessed from within resources.

abstract Boolean

Returns whether AppCompat handles any native action modes itself.

abstract Unit

Should be called from onConfigurationChanged

abstract Unit
onCreate(savedInstanceState: Bundle!)

Should be called from Activity.onCreate().

abstract Unit

Should be called from onDestroy

abstract Unit
onPostCreate(savedInstanceState: Bundle!)

Should be called from onPostCreate

abstract Unit

Should be called from onPostResume

abstract Unit

Allows AppCompat to save instance state.

abstract Unit

Should be called from onStart Activity.onStart()}

abstract Unit

Should be called from Activity.onStop()

abstract Boolean

Enable extended window features.

java-static Unit

Sets the current locales for the calling app.

java-static Unit

Sets whether vector drawables on older platforms (< API 21) can be used within android.graphics.drawable.DrawableContainer resources.

abstract Unit

Should be called instead of setContentView}

abstract Unit

Should be called instead of setContentView}

abstract Unit

Should be called instead of setContentView}

java-static Unit

Sets the default night mode.

abstract Unit

Whether AppCompat handles any native action modes itself.

abstract Unit

Override the night mode used for this delegate's host component.

Unit

Sets the OnBackInvokedDispatcher for handling system back for Android SDK 33 and above.

abstract Unit

Set a Toolbar to act as the ActionBar for this delegate.

Unit
setTheme(themeResId: @StyleRes Int)

This should be called from setTheme to notify AppCompat of what the current theme resource id is.

abstract Unit

Should be called from onTitleChanged}

abstract ActionMode?

Start an action mode.

Constants

FEATURE_ACTION_MODE_OVERLAY

Added in 1.1.0
const val FEATURE_ACTION_MODE_OVERLAY = 10: Int

Flag for specifying the behavior of action modes when an Action Bar is not present. If overlay is enabled, the action mode UI will be allowed to cover existing window content.

FEATURE_SUPPORT_ACTION_BAR

Added in 1.1.0
const val FEATURE_SUPPORT_ACTION_BAR = 108: Int

Flag for enabling the support Action Bar.

This is enabled by default for some devices. The Action Bar replaces the title bar and provides an alternate location for an on-screen menu button on some devices.

FEATURE_SUPPORT_ACTION_BAR_OVERLAY

Added in 1.1.0
const val FEATURE_SUPPORT_ACTION_BAR_OVERLAY = 109: Int

Flag for requesting an support Action Bar that overlays window content. Normally an Action Bar will sit in the space above window content, but if this feature is requested along with FEATURE_SUPPORT_ACTION_BAR it will be layered over the window content itself. This is useful if you would like your app to have more control over how the Action Bar is displayed, such as letting application content scroll beneath an Action Bar with a transparent background or otherwise displaying a transparent/translucent Action Bar over application content.

This mode is especially useful with View.SYSTEM_UI_FLAG_FULLSCREEN, which allows you to seamlessly hide the action bar in conjunction with other screen decorations. When an ActionBar is in this mode it will adjust the insets provided to View.fitSystemWindows(Rect) to include the content covered by the action bar, so you can do layout within that space.

MODE_NIGHT_AUTO

Added in 1.1.0
Deprecated in 1.1.0
const val MODE_NIGHT_AUTO = 0: Int

MODE_NIGHT_AUTO_BATTERY

Added in 1.1.0
const val MODE_NIGHT_AUTO_BATTERY = 3: Int

Night mode which uses a dark mode when the system's 'Battery Saver' feature is enabled, otherwise it uses a 'light mode'. This mode can help the device to decrease power usage, depending on the display technology in the device. Please note: this mode should only be used when running on devices which do not provide a similar device-wide setting.

MODE_NIGHT_AUTO_TIME

Added in 1.1.0
Deprecated in 1.1.0
const val MODE_NIGHT_AUTO_TIME = 0: Int

Night mode which switches between dark and light mode depending on the time of day (dark at night, light in the day).

The calculation used to determine whether it is night or not makes use of the location APIs (if this app has the necessary permissions). This allows us to generate accurate sunrise and sunset times. If this app does not have permission to access the location APIs then we use hardcoded times which will be less accurate.

MODE_NIGHT_FOLLOW_SYSTEM

Added in 1.1.0
const val MODE_NIGHT_FOLLOW_SYSTEM = -1: Int

Mode which uses the system's night mode setting to determine if it is night or not.

MODE_NIGHT_NO

Added in 1.1.0
const val MODE_NIGHT_NO = 1: Int

Night mode which uses always uses a light mode, enabling notnight qualified resources regardless of the time.

MODE_NIGHT_UNSPECIFIED

Added in 1.1.0
const val MODE_NIGHT_UNSPECIFIED = -100: Int

An unspecified mode for night mode. This is primarily used with setLocalNightMode, to allow the default night mode to be used. If both the default and local night modes are set to this value, then the default value of MODE_NIGHT_FOLLOW_SYSTEM is applied.

MODE_NIGHT_YES

Added in 1.1.0
const val MODE_NIGHT_YES = 2: Int

Night mode which uses always uses a dark mode, enabling night qualified resources regardless of the time.

Public functions

addContentView

Added in 1.1.0
abstract fun addContentView(v: View!, lp: ViewGroup.LayoutParams!): Unit

Should be called instead of addContentView}

applyDayNight

Added in 1.1.0
abstract fun applyDayNight(): Boolean

Applies the currently selected night mode to this delegate's host component.

This enables the Theme.AppCompat.DayNight family of themes to work, using the specified mode.

You can be notified when the night changes by overriding the onNightModeChanged method.

Returns
Boolean

true if the night mode was applied, false if not

attachBaseContext

Added in 1.1.0
Deprecated in 1.2.0
fun attachBaseContext(context: Context!): Unit

attachBaseContext2

Added in 1.2.0
@CallSuper
fun attachBaseContext2(context: Context): Context

Should be called from attachBaseContext.

create

Added in 1.1.0
java-static fun create(activity: Activity, callback: AppCompatCallback?): AppCompatDelegate

Create an androidx.appcompat.app.AppCompatDelegate to use with activity.

Parameters
callback: AppCompatCallback?

An optional callback for AppCompat specific events

create

Added in 1.1.0
java-static fun create(dialog: Dialog, callback: AppCompatCallback?): AppCompatDelegate

Create an androidx.appcompat.app.AppCompatDelegate to use with dialog.

Parameters
callback: AppCompatCallback?

An optional callback for AppCompat specific events

create

Added in 1.1.0
java-static fun create(context: Context, activity: Activity, callback: AppCompatCallback?): AppCompatDelegate

Create an androidx.appcompat.app.AppCompatDelegate to use with a context and hosted by an Activity.

Parameters
callback: AppCompatCallback?

An optional callback for AppCompat specific events

create

Added in 1.1.0
java-static fun create(context: Context, window: Window, callback: AppCompatCallback?): AppCompatDelegate

Create an androidx.appcompat.app.AppCompatDelegate to use with a context and a window.

Parameters
callback: AppCompatCallback?

An optional callback for AppCompat specific events

createView

Added in 1.1.0
abstract fun createView(parent: View?, name: String!, context: Context, attrs: AttributeSet): View!

This should be called from a LayoutInflater.Factory2 in order to return tint-aware widgets.

This is only needed if you are using your own LayoutInflater factory, and have therefore not installed the default factory via installViewFactory.

findViewById

Added in 1.1.0
abstract fun <T : View?> findViewById(id: @IdRes Int): T?

Finds a view that was identified by the id attribute from the XML that was processed in onCreate.

Returns
T?

The view if found or null otherwise.

getApplicationLocales

Added in 1.6.0
@AnyThread
java-static fun getApplicationLocales(): LocaleListCompat

Returns application locales for the calling app as a LocaleListCompat.

Returns a getEmptyLocaleList if no app-specific locales are set.

Note: This API only work at AppCompatDelegate and it should always be called after Activity.onCreate().

getContextForDelegate

Added in 1.6.0
fun getContextForDelegate(): Context?

Returns the context for the current delegate.

getDefaultNightMode

Added in 1.1.0
java-static fun getDefaultNightMode(): Int

Returns the default night mode.

getDrawerToggleDelegate

Added in 1.1.0
abstract fun getDrawerToggleDelegate(): ActionBarDrawerToggle.Delegate?

Returns an ActionBarDrawerToggle.Delegate which can be returned from your Activity if it implements ActionBarDrawerToggle.DelegateProvider.

getLocalNightMode

Added in 1.1.0
fun getLocalNightMode(): Int

Returns the night mode previously set via getLocalNightMode.

getMenuInflater

Added in 1.1.0
abstract fun getMenuInflater(): MenuInflater!

Return the value of this call from your getMenuInflater

getSupportActionBar

Added in 1.1.0
abstract fun getSupportActionBar(): ActionBar?

Support library version of getActionBar.

Returns
ActionBar?

AppCompat's action bar, or null if it does not have one.

hasWindowFeature

Added in 1.1.0
abstract fun hasWindowFeature(featureId: Int): Boolean

Query for the availability of a certain feature.

This should be called instead of hasFeature.

Parameters
featureId: Int

The feature ID to check

Returns
Boolean

true if the feature is enabled, false otherwise.

installViewFactory

Added in 1.1.0
abstract fun installViewFactory(): Unit

Installs AppCompat's android.view.LayoutInflater Factory so that it can replace the framework widgets with compatible tinted versions. This should be called before super.onCreate() as so:

protected void onCreate(Bundle savedInstanceState) {
    getDelegate().installViewFactory();
    getDelegate().onCreate(savedInstanceState);
    super.onCreate(savedInstanceState);

    // ...
}
If you are using your own Factory or Factory2 then you can omit this call, and instead call createView from your factory to return any compatible widgets.

invalidateOptionsMenu

Added in 1.1.0
abstract fun invalidateOptionsMenu(): Unit

Should be called from invalidateOptionsMenu} or supportInvalidateOptionsMenu.

isCompatVectorFromResourcesEnabled

Added in 1.1.0
java-static fun isCompatVectorFromResourcesEnabled(): Boolean

Returns whether vector drawables on older platforms (< API 21) can be accessed from within resources.

isHandleNativeActionModesEnabled

Added in 1.1.0
abstract fun isHandleNativeActionModesEnabled(): Boolean

Returns whether AppCompat handles any native action modes itself.

Returns
Boolean

true if AppCompat should handle native action modes.

onConfigurationChanged

Added in 1.1.0
abstract fun onConfigurationChanged(newConfig: Configuration!): Unit

Should be called from onConfigurationChanged

onCreate

Added in 1.1.0
abstract fun onCreate(savedInstanceState: Bundle!): Unit

Should be called from Activity.onCreate().

This should be called before super.onCreate() as so:

protected void onCreate(Bundle savedInstanceState) {
    getDelegate().onCreate(savedInstanceState);
    super.onCreate(savedInstanceState);
    // ...
}

onDestroy

Added in 1.1.0
abstract fun onDestroy(): Unit

Should be called from onDestroy

onPostCreate

Added in 1.1.0
abstract fun onPostCreate(savedInstanceState: Bundle!): Unit

Should be called from onPostCreate

onPostResume

Added in 1.1.0
abstract fun onPostResume(): Unit

Should be called from onPostResume

onSaveInstanceState

Added in 1.1.0
abstract fun onSaveInstanceState(outState: Bundle!): Unit

Allows AppCompat to save instance state.

onStart

Added in 1.1.0
abstract fun onStart(): Unit

Should be called from onStart Activity.onStart()}

onStop

Added in 1.1.0
abstract fun onStop(): Unit

Should be called from Activity.onStop()

requestWindowFeature

Added in 1.1.0
abstract fun requestWindowFeature(featureId: Int): Boolean

Enable extended window features. This should be called instead of requestWindowFeature or getWindow().requestFeature().

Parameters
featureId: Int

The desired feature as defined in android.view.Window.

Returns
Boolean

Returns true if the requested feature is supported and now enabled.

setApplicationLocales

Added in 1.6.0
java-static fun setApplicationLocales(locales: LocaleListCompat): Unit

Sets the current locales for the calling app.

If this method is called after any host components with attached AppCompatDelegates have been 'created', a LocaleList configuration change will occur in each. This may result in those components being recreated, depending on their manifest configuration.

This method accepts LocaleListCompat as an input parameter.

Apps should continue to read Locales via their in-process LocaleLists.

Pass a getEmptyLocaleList to reset to the system locale.

Note: This API should always be called after Activity.onCreate(), apart from any exceptions explicitly mentioned in this documentation.

On API level 33 and above, this API will handle storage automatically.

For API levels below that, the developer has two options:

  • They can opt-in to automatic storage handled through the library. They can do this by adding a special metaData entry in their AndroidManifest.xml, similar to :
        <service
            android:name="androidx.appcompat.app.AppLocalesMetadataHolderService"
            android:enabled="false"
            android:exported="false">
            <meta-data
                android:name="autoStoreLocales"
                android:value="true" />
        </service>
    They should be mindful that this will cause a blocking diskRead and diskWrite strictMode violation, and they might need to suppress it at their end.
  • The second option is that they can choose to handle storage themselves. In order to do so they must use this API to initialize locales during app-start up and provide their stored locales. In this case, API should be called before Activity.onCreate() in the activity lifecycle, e.g. in attachBaseContext(). Note: Developers should gate this to API versions <33.

    This API should be called after Activity.onCreate() for all other cases.

When the application using this API with API versions <33 updates to a version >= 33, then there can be two scenarios for this transition:

  • If the developer has opted-in for autoStorage then the locales will be automatically synced to the framework. Developers must specify android:enabled="false" for the AppLocalesMetadataHolderService as shown in the meta-data entry above.
  • If the developer has not opted-in for autoStorage then they will need to handle this transition on their end.

Note: This API work with the AppCompatActivity context, not for others context, for Android 12 (API level 32) and earlier. If there is a requirement to get the localized string which respects the per-app locale in non-AppCompatActivity context, please consider using getString or getContextForLanguage.

Parameters
locales: LocaleListCompat

a list of locales.

setCompatVectorFromResourcesEnabled

Added in 1.1.0
java-static fun setCompatVectorFromResourcesEnabled(enabled: Boolean): Unit

Sets whether vector drawables on older platforms (< API 21) can be used within android.graphics.drawable.DrawableContainer resources.

When enabled, AppCompat can intercept some drawable inflation from the framework, which enables implicit inflation of vector drawables within android.graphics.drawable.DrawableContainer resources. You can then use those drawables in places such as android:src on android.widget.ImageView, or android:drawableLeft on android.widget.TextView. Example usage:

<selector xmlns:android="...">
    <item android:state_checked="true"
          android:drawable="@drawable/vector_checked_icon" />
    <item android:drawable="@drawable/vector_icon" />
</selector>

<TextView
        ...
        android:drawableLeft="@drawable/vector_state_list_icon" />

This feature defaults to disabled, since enabling it can cause issues with memory usage, and problems updating Configuration instances. If you update the configuration manually, then you probably do not want to enable this. You have been warned.

Even with this disabled, you can still use vector resources through setImageResource and its app:srcCompat attribute. They can also be used in anything which AppCompat inflates for you, such as menu resources.

Please note: this only takes effect in Activities created after this call.

setContentView

Added in 1.1.0
abstract fun setContentView(resId: @LayoutRes Int): Unit

Should be called instead of setContentView}

setContentView

Added in 1.1.0
abstract fun setContentView(v: View!): Unit

Should be called instead of setContentView}

setContentView

Added in 1.1.0
abstract fun setContentView(v: View!, lp: ViewGroup.LayoutParams!): Unit

Should be called instead of setContentView}

setDefaultNightMode

Added in 1.1.0
java-static fun setDefaultNightMode(mode: Int): Unit

Sets the default night mode. This is the default value used for all components, but can be overridden locally via setLocalNightMode.

This is the primary method to control the DayNight functionality, since it allows the delegates to avoid unnecessary recreations when possible.

If this method is called after any host components with attached AppCompatDelegates have been 'created', a uiMode configuration change will occur in each. This may result in those components being recreated, depending on their manifest configuration.

Defaults to MODE_NIGHT_FOLLOW_SYSTEM.

setHandleNativeActionModesEnabled

Added in 1.1.0
abstract fun setHandleNativeActionModesEnabled(enabled: Boolean): Unit

Whether AppCompat handles any native action modes itself.

This methods only takes effect on ICE_CREAM_SANDWICH and above.

Parameters
enabled: Boolean

whether AppCompat should handle native action modes.

setLocalNightMode

Added in 1.1.0
abstract fun setLocalNightMode(mode: Int): Unit

Override the night mode used for this delegate's host component.

When setting a mode to be used across an entire app, the setDefaultNightMode method is preferred.

If this is called after the host component has been created, a uiMode configuration change will occur, which may result in the component being recreated.

It is not recommended to use this method on a delegate attached to a Dialog. Dialogs use the host Activity as their context, resulting in the dialog's night mode overriding the Activity's night mode.

Note: This method is not recommended for use on devices running SDK 16 or earlier, as the specified night mode configuration may leak to other activities. Instead, consider using setDefaultNightMode to specify an app-wide night mode.

setOnBackInvokedDispatcher

Added in 1.6.0
@CallSuper
@RequiresApi(value = 33)
fun setOnBackInvokedDispatcher(dispatcher: OnBackInvokedDispatcher?): Unit

Sets the OnBackInvokedDispatcher for handling system back for Android SDK 33 and above.

If the delegate is hosted by an Activity, the default dispatcher is obtained via getOnBackInvokedDispatcher.

Parameters
dispatcher: OnBackInvokedDispatcher?

the OnBackInvokedDispatcher to be set on this delegate, or null to use the default dispatcher

setSupportActionBar

Added in 1.1.0
abstract fun setSupportActionBar(toolbar: Toolbar?): Unit

Set a Toolbar to act as the ActionBar for this delegate.

When set to a non-null value the getSupportActionBar ()} method will return an ActionBar object that can be used to control the given toolbar as if it were a traditional window decor action bar. The toolbar's menu will be populated with the Activity's options menu and the navigation button will be wired through the standard home menu select action.

In order to use a Toolbar within the Activity's window content the application must not request the window feature FEATURE_SUPPORT_ACTION_BAR.

Parameters
toolbar: Toolbar?

Toolbar to set as the Activity's action bar, or null to clear it

setTheme

Added in 1.1.0
fun setTheme(themeResId: @StyleRes Int): Unit

This should be called from setTheme to notify AppCompat of what the current theme resource id is.

setTitle

Added in 1.1.0
abstract fun setTitle(title: CharSequence?): Unit

Should be called from onTitleChanged}

startSupportActionMode

Added in 1.1.0
abstract fun startSupportActionMode(callback: ActionMode.Callback): ActionMode?

Start an action mode.

Parameters
callback: ActionMode.Callback

Callback that will manage lifecycle events for this context mode

Returns
ActionMode?

The ContextMode that was started, or null if it was canceled