ComponentActivity
open class ComponentActivity : Activity, LifecycleOwner, ContextAware, ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner, OnBackPressedDispatcherOwner, NavigationEventDispatcherOwner, ActivityResultRegistryOwner, ActivityResultCaller, OnConfigurationChangedProvider, OnTrimMemoryProvider, OnNewIntentProvider, OnMultiWindowModeChangedProvider, OnPictureInPictureModeChangedProvider, OnUserLeaveHintProvider, MenuHost, FullyDrawnReporterOwner
| kotlin.Any | |||||
| ↳ | android.content.Context | ||||
| ↳ | android.content.ContextWrapper | ||||
| ↳ | android.view.ContextThemeWrapper | ||||
| ↳ | android.app.Activity | ||||
| ↳ | androidx.activity.ComponentActivity |
FragmentActivity |
Base class for activities that want to use the support-based |
PreviewActivity |
Activity used to run |
AppCompatActivity |
Base class for activities that wish to use some of the newer platform features on older Android devices. |
BaseCarAppActivity |
Core logic for CarAppLibrary Activity interaction with a host. |
CarAppActivity |
The class representing a car app activity in the main display. |
LauncherActivity |
This class handles providing the right launcher activity when running native applications and Car App Library applications. |
Base class for activities that enables composition of higher level components.
Rather than all functionality being built directly into this class, only the minimal set of lower level building blocks are included. Higher level components can then be used as needed without enforcing a deep Activity class hierarchy or strong coupling between components.
Summary
Public constructors |
|---|
@ContentViewAlternate constructor that can be used to provide a default layout that will be inflated as part of |
Public functions |
|
|---|---|
open Unit |
addContentView(view: View?, params: ViewGroup.LayoutParams?) |
open Unit |
addMenuProvider(provider: MenuProvider)Adds the given |
open Unit |
addMenuProvider(provider: MenuProvider, owner: LifecycleOwner)Adds the given |
open Unit |
addMenuProvider(Adds the given |
final Unit |
addOnConfigurationChangedListener(listener: Consumer<Configuration>)Add a new listener that will get a callback associated with ComponentCallbacks.onConfigurationChanged with the new |
final Unit |
{@inheritDoc} |
final Unit |
Add a new listener that will get a callback associated with |
final Unit |
addOnNewIntentListener(listener: Consumer<Intent>)Add a new listener that will get a callback associated with |
final Unit |
Add a new listener that will get a callback associated with |
final Unit |
addOnTrimMemoryListener(listener: Consumer<Int>)Add a new listener that will get a callback associated with ComponentCallbacks2.onTrimMemory with the |
final Unit |
addOnUserLeaveHintListener(listener: Runnable)Add a new listener that will get a callback associated with |
open Unit |
Sets the view tree owners before setting the content view so that the inflation process and attach listeners will see them already present. |
open Unit |
Invalidates the |
open Unit |
This function is deprecated. This method has been deprecated in favor of using the {@link OnBackPressedDispatcher} via {@link #getOnBackPressedDispatcher()}. |
open Unit |
@CallSuper{@inheritDoc} |
open Boolean |
onCreatePanelMenu(featureId: Int, menu: Menu) |
open Boolean |
onMenuItemSelected(featureId: Int, item: MenuItem) |
open Unit |
@CallSuperThis function is deprecated. Deprecated in android.app.Activity |
open Unit |
@RequiresApi(api = 26){@inheritDoc} |
open Unit |
onPanelClosed(featureId: Int, menu: Menu) |
open Unit |
@CallSuperThis function is deprecated. Deprecated in android.app.Activity |
open Unit |
@RequiresApi(api = 26){@inheritDoc} |
open Boolean |
onPreparePanel(featureId: Int, view: View?, menu: Menu) |
open Unit |
@CallSuperThis function is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an {@link ActivityResultContract} and the prebuilt contracts for common intents available in {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity. |
open Any? |
This function is deprecated. Use a {@link androidx.lifecycle.ViewModel} to store non config state. |
final Any? |
Retain all appropriate non-config state. |
open Unit |
@CallSuper{@inheritDoc} |
open Context? |
Get the |
final ActivityResultLauncher<I> |
<I : Any?, O : Any?> registerForActivityResult(Register a request to |
final ActivityResultLauncher<I> |
<I : Any?, O : Any?> registerForActivityResult(Register a request to |
open Unit |
removeMenuProvider(provider: MenuProvider)Removes the given |
final Unit |
Remove a previously added listener. |
final Unit |
Remove a |
final Unit |
Remove a previously added listener. |
final Unit |
removeOnNewIntentListener(listener: Consumer<Intent>)Remove a previously added listener. |
final Unit |
Remove a previously added listener. |
final Unit |
removeOnTrimMemoryListener(listener: Consumer<Int>)Remove a previously added listener. |
final Unit |
removeOnUserLeaveHintListener(listener: Runnable)Remove a previously added listener. |
open Unit |
|
open Unit |
setContentView(layoutResID: @LayoutRes Int) |
open Unit |
setContentView(view: View?) |
open Unit |
setContentView(view: View?, params: ViewGroup.LayoutParams?) |
open Unit |
This function is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an {@link ActivityResultContract} and the prebuilt contracts for common intents available in {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity. |
open Unit |
This function is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an {@link ActivityResultContract} and the prebuilt contracts for common intents available in {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity. |
open Unit |
This function is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an {@link ActivityResultContract} and the prebuilt contracts for common intents available in {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity. |
open Unit |
This function is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an {@link ActivityResultContract} and the prebuilt contracts for common intents available in {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity. |
Protected functions |
|
|---|---|
open Unit |
@CallSuperThis function is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an {@link ActivityResultContract} and the prebuilt contracts for common intents available in {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity. |
open Unit |
{@inheritDoc} |
open Unit |
@CallSuper{@inheritDoc} |
open Unit |
@CallSuper |
open Unit |
{@inheritDoc} |
Public properties |
|
|---|---|
final ActivityResultRegistry |
Get the |
open CreationExtras |
|
open ViewModelProvider.Factory |
|
open FullyDrawnReporter |
Retrieve the |
open Any? |
|
open Lifecycle |
{@inheritDoc} |
open NavigationEventDispatcher |
Lazily provides a |
final OnBackPressedDispatcher |
Retrieve the |
final SavedStateRegistry |
|
open ViewModelStore |
Extension functions |
|
|---|---|
inline Lazy<VM> |
@MainThreadReturns a |
Unit |
ComponentActivity.setContent(Composes the given composable into the given activity. |
Unit |
ComponentActivity.enableEdgeToEdge(Enables the edge-to-edge display for this |
Public constructors
ComponentActivity
@ContentView
ComponentActivity(contentLayoutId: @LayoutRes Int)
Alternate constructor that can be used to provide a default layout that will be inflated as part of super.onCreate(savedInstanceState).
This should generally be called from your constructor that takes no parameters, as is required for API 27 and lower or when using the default android.app.AppComponentFactory.
Public functions
addMenuProvider
open fun addMenuProvider(provider: MenuProvider): Unit
Adds the given MenuProvider to this MenuHost. If using this method, you must manually remove the provider when necessary.
| Parameters | |
|---|---|
provider: MenuProvider |
the MenuProvider to be added |
| See also | |
|---|---|
removeMenuProvider |
addMenuProvider
open fun addMenuProvider(provider: MenuProvider, owner: LifecycleOwner): Unit
Adds the given MenuProvider to this MenuHost. This MenuProvider will be removed once the given LifecycleOwner receives an Lifecycle.Event.ON_DESTROY event.
| Parameters | |
|---|---|
provider: MenuProvider |
the MenuProvider to be added |
owner: LifecycleOwner |
the Lifecycle owner whose state will determine the removal of the provider |
addMenuProvider
open fun addMenuProvider(
provider: MenuProvider,
owner: LifecycleOwner,
state: Lifecycle.State
): Unit
Adds the given MenuProvider to this MenuHost once the given LifecycleOwner reaches the given Lifecycle.State. This MenuProvider will be removed once the given LifecycleOwner goes down from the given Lifecycle.State.
| Parameters | |
|---|---|
provider: MenuProvider |
the MenuProvider to be added |
owner: LifecycleOwner |
the Lifecycle owner whose state will be used for automated addition/removal |
state: Lifecycle.State |
the Lifecycle.State to check for automated addition/removal |
addOnConfigurationChangedListener
final fun addOnConfigurationChangedListener(listener: Consumer<Configuration>): Unit
Add a new listener that will get a callback associated with ComponentCallbacks.onConfigurationChanged with the new Configuration.
| Parameters | |
|---|---|
listener: Consumer<Configuration> |
The listener that should be called whenever {ComponentCallbacks.onConfigurationChanged was called. |
addOnContextAvailableListener
final fun addOnContextAvailableListener(listener: OnContextAvailableListener): Unit
{@inheritDoc}
Any listener added here will receive a callback as part of super.onCreate(), but importantly before any other logic is done (including calling through to the framework Activity.onCreate with the exception of restoring the state of the savedStateRegistry for use in your listener.
addOnMultiWindowModeChangedListener
final fun addOnMultiWindowModeChangedListener(
listener: Consumer<MultiWindowModeChangedInfo>
): Unit
Add a new listener that will get a callback associated with Activity.onMultiWindowModeChanged with the new MultiWindowModeChangedInfo.
| Parameters | |
|---|---|
listener: Consumer<MultiWindowModeChangedInfo> |
The listener that should be called whenever Activity#onMultiWindowModeChanged was called. |
addOnNewIntentListener
final fun addOnNewIntentListener(listener: Consumer<Intent>): Unit
Add a new listener that will get a callback associated with Activity.onNewIntent with the new Intent.
addOnPictureInPictureModeChangedListener
final fun addOnPictureInPictureModeChangedListener(
listener: Consumer<PictureInPictureModeChangedInfo>
): Unit
Add a new listener that will get a callback associated with Activity.onPictureInPictureModeChanged with the new PictureInPictureModeChangedInfo.
| Parameters | |
|---|---|
listener: Consumer<PictureInPictureModeChangedInfo> |
The listener that should be called whenever |
addOnTrimMemoryListener
final fun addOnTrimMemoryListener(listener: Consumer<Int>): Unit
Add a new listener that will get a callback associated with ComponentCallbacks2.onTrimMemory with the int representing the level of trimming.
addOnUserLeaveHintListener
final fun addOnUserLeaveHintListener(listener: Runnable): Unit
Add a new listener that will get a callback associated with Activity.onUserLeaveHint
| Parameters | |
|---|---|
listener: Runnable |
The listener that should be called whenever |
initializeViewTreeOwners
@CallSuper
open fun initializeViewTreeOwners(): Unit
Sets the view tree owners before setting the content view so that the inflation process and attach listeners will see them already present.
invalidateMenu
open fun invalidateMenu(): Unit
Invalidates the android.view.Menu to ensure that what is displayed matches the current internal state of the menu. This should be called whenever the state of the menu is changed, such as items being removed or disabled based on some user event.
onBackPressed
@MainThread
@CallSuper
open funonBackPressed(): Unit
Called when the activity has detected the user's press of the back key. The onBackPressedDispatcher will be given a chance to handle the back button before the default behavior of android.app.Activity.onBackPressed is invoked.
| See also | |
|---|---|
onBackPressedDispatcher |
onConfigurationChanged
@CallSuper
open fun onConfigurationChanged(newConfig: Configuration): Unit
{@inheritDoc}
Dispatches this call to all listeners added via addOnConfigurationChangedListener.
onMultiWindowModeChanged
@CallSuper
open funonMultiWindowModeChanged(isInMultiWindowMode: Boolean): Unit
{@inheritDoc}
Dispatches this call to all listeners added via addOnMultiWindowModeChangedListener.
onMultiWindowModeChanged
@RequiresApi(api = 26)
@CallSuper
open fun onMultiWindowModeChanged(
isInMultiWindowMode: Boolean,
newConfig: Configuration
): Unit
{@inheritDoc}
Dispatches this call to all listeners added via addOnMultiWindowModeChangedListener.
onPictureInPictureModeChanged
@CallSuper
open funonPictureInPictureModeChanged(isInPictureInPictureMode: Boolean): Unit
{@inheritDoc}
Dispatches this call to all listeners added via addOnPictureInPictureModeChangedListener.
onPictureInPictureModeChanged
@RequiresApi(api = 26)
@CallSuper
open fun onPictureInPictureModeChanged(
isInPictureInPictureMode: Boolean,
newConfig: Configuration
): Unit
{@inheritDoc}
Dispatches this call to all listeners added via addOnPictureInPictureModeChangedListener.
@CallSuper
open funonRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
): Unit
{@inheritDoc}
open funonRetainCustomNonConfigurationInstance(): Any?
Use this instead of onRetainNonConfigurationInstance. Retrieve later with lastCustomNonConfigurationInstance.
onRetainNonConfigurationInstance
final fun onRetainNonConfigurationInstance(): Any?
Retain all appropriate non-config state. You can NOT override this yourself! Use a androidx.lifecycle.ViewModel if you want to retain your own non config state.
onTrimMemory
@CallSuper
open fun onTrimMemory(level: Int): Unit
{@inheritDoc}
Dispatches this call to all listeners added via addOnTrimMemoryListener.
peekAvailableContext
open fun peekAvailableContext(): Context?
Get the Context if it is currently available. If this returns null, you can use addOnContextAvailableListener to receive a callback for when it available.
| Returns | |
|---|---|
Context? |
the Context if it is currently available. |
registerForActivityResult
final fun <I : Any?, O : Any?> registerForActivityResult(
contract: ActivityResultContract<I, O>,
callback: ActivityResultCallback<O>
): ActivityResultLauncher<I>
Register a request to start an activity for result, designated by the given contract.
This creates a record in the registry associated with this caller, managing request code, as well as conversions to/from Intent under the hood.
This must be called unconditionally, as part of initialization path, typically as a field initializer of an Activity or Fragment.
| Parameters | |
|---|---|
<I : Any?> |
the type of the input(if any) required to call the activity |
<O : Any?> |
the type of output returned as an activity result |
contract: ActivityResultContract<I, O> |
the contract, specifying conversions to/from |
callback: ActivityResultCallback<O> |
the callback to be called on the main thread when activity result is available |
| Returns | |
|---|---|
ActivityResultLauncher<I> |
the launcher that can be used to start the activity or dispose of the prepared call. |
registerForActivityResult
final fun <I : Any?, O : Any?> registerForActivityResult(
contract: ActivityResultContract<I, O>,
registry: ActivityResultRegistry,
callback: ActivityResultCallback<O>
): ActivityResultLauncher<I>
Register a request to start an activity for result, designated by the given contract.
This creates a record in the given registry, managing request code, as well as conversions to/from Intent under the hood.
This must be called unconditionally, as part of initialization path, typically as a field initializer of an Activity or Fragment.
| Parameters | |
|---|---|
<I : Any?> |
the type of the input(if any) required to call the activity |
<O : Any?> |
the type of output returned as an activity result |
contract: ActivityResultContract<I, O> |
the contract, specifying conversions to/from |
registry: ActivityResultRegistry |
the registry where to hold the record. |
callback: ActivityResultCallback<O> |
the callback to be called on the main thread when activity result is available |
| Returns | |
|---|---|
ActivityResultLauncher<I> |
the launcher that can be used to start the activity or dispose of the prepared call. |
removeMenuProvider
open fun removeMenuProvider(provider: MenuProvider): Unit
Removes the given MenuProvider from this MenuHost.
| Parameters | |
|---|---|
provider: MenuProvider |
the MenuProvider to be removed |
removeOnConfigurationChangedListener
final fun removeOnConfigurationChangedListener(listener: Consumer<Configuration>): Unit
Remove a previously added listener. It will not receive any future callbacks.
| Parameters | |
|---|---|
listener: Consumer<Configuration> |
The listener previously added with |
removeOnContextAvailableListener
final fun removeOnContextAvailableListener(listener: OnContextAvailableListener): Unit
Remove a OnContextAvailableListener previously added via addOnContextAvailableListener.
| Parameters | |
|---|---|
listener: OnContextAvailableListener |
The listener that should be removed. |
| See also | |
|---|---|
addOnContextAvailableListener |
removeOnMultiWindowModeChangedListener
final fun removeOnMultiWindowModeChangedListener(
listener: Consumer<MultiWindowModeChangedInfo>
): Unit
Remove a previously added listener. It will not receive any future callbacks.
| Parameters | |
|---|---|
listener: Consumer<MultiWindowModeChangedInfo> |
The listener previously added with |
removeOnNewIntentListener
final fun removeOnNewIntentListener(listener: Consumer<Intent>): Unit
Remove a previously added listener. It will not receive any future callbacks.
| Parameters | |
|---|---|
listener: Consumer<Intent> |
The listener previously added with |
removeOnPictureInPictureModeChangedListener
final fun removeOnPictureInPictureModeChangedListener(
listener: Consumer<PictureInPictureModeChangedInfo>
): Unit
Remove a previously added listener. It will not receive any future callbacks.
| Parameters | |
|---|---|
listener: Consumer<PictureInPictureModeChangedInfo> |
The listener previously added with |
removeOnTrimMemoryListener
final fun removeOnTrimMemoryListener(listener: Consumer<Int>): Unit
Remove a previously added listener. It will not receive any future callbacks.
removeOnUserLeaveHintListener
final fun removeOnUserLeaveHintListener(listener: Runnable): Unit
Remove a previously added listener. It will not receive any future callbacks.
| Parameters | |
|---|---|
listener: Runnable |
The listener previously added with |
open funstartActivityForResult(intent: Intent, requestCode: Int, options: Bundle?): Unit
{@inheritDoc}
open funstartIntentSenderForResult(
intent: IntentSender,
requestCode: Int,
fillInIntent: Intent?,
flagsMask: Int,
flagsValues: Int,
extraFlags: Int
): Unit
{@inheritDoc}
Protected functions
@CallSuper
protected open funonActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Unit
{@inheritDoc}
onCreate
protected open fun onCreate(savedInstanceState: Bundle?): Unit
{@inheritDoc}
If your ComponentActivity is annotated with ContentView, this will call setContentView for you.
onNewIntent
@CallSuper
protected open fun onNewIntent(intent: Intent): Unit
{@inheritDoc}
Dispatches this call to all listeners added via addOnNewIntentListener.
onUserLeaveHint
@CallSuper
protected open fun onUserLeaveHint(): Unit
{@inheritDoc}
Dispatches this call to all listeners added via addOnUserLeaveHintListener.
Public properties
activityResultRegistry
final val activityResultRegistry: ActivityResultRegistry
Get the ActivityResultRegistry associated with this activity.
| Returns | |
|---|---|
ActivityResultRegistry |
defaultViewModelProviderFactory
open val defaultViewModelProviderFactory: ViewModelProvider.Factory
fullyDrawnReporter
open val fullyDrawnReporter: FullyDrawnReporter
Retrieve the FullyDrawnReporter that should handle the independent parts of the UI that separately report that they are fully drawn.
lifecycle
open val lifecycle: Lifecycle
{@inheritDoc}
Overriding this method is no longer supported and this method will be made final in a future version of ComponentActivity. If you do override this method, you must:
-
Return an instance of
LifecycleRegistry -
Lazily initialize your LifecycleRegistry object when this is first called.
Note that this method will be called in the super classes' constructor, before any field initialization or object state creation is complete.
navigationEventDispatcher
open val navigationEventDispatcher: NavigationEventDispatcher
Lazily provides a NavigationEventDispatcher for back navigation handling, including support for predictive back gestures introduced in Android 13 (API 33+).
This dispatcher acts as the central point for back navigation events. When a navigation event occurs (e.g., a back gesture), it safely invokes ComponentActivity.onBackPressed.
onBackPressedDispatcher
final val onBackPressedDispatcher: OnBackPressedDispatcher
Retrieve the OnBackPressedDispatcher that will be triggered when onBackPressed is called.
| Returns | |
|---|---|
OnBackPressedDispatcher |
The |
Extension functions
viewModels
@MainThread
inline fun <VM : ViewModel> ComponentActivity.viewModels(
noinline extrasProducer: (() -> CreationExtras)? = null,
noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
): Lazy<VM>
Returns a Lazy delegate to access the ComponentActivity's ViewModel, if factoryProducer is specified then ViewModelProvider.Factory returned by it will be used to create ViewModel first time.
class MyComponentActivity : ComponentActivity() {
val viewmodel: MyViewModel by viewModels()
}
This property can be accessed only after the Activity is attached to the Application, and access prior to that will result in IllegalArgumentException.
setContent
fun ComponentActivity.setContent(
parent: CompositionContext? = null,
content: @Composable () -> Unit
): Unit
Composes the given composable into the given activity. The content will become the root view of the given activity.
This is roughly equivalent to calling ComponentActivity.setContentView with a ComposeView i.e.:
setContentView(
ComposeView(this).apply {
setContent {
MyComposableContent()
}
}
)
| Parameters | |
|---|---|
parent: CompositionContext? = null |
The parent composition reference to coordinate scheduling of composition updates |
content: @Composable () -> Unit |
A |
enableEdgeToEdge
fun ComponentActivity.enableEdgeToEdge(
statusBarStyle: SystemBarStyle = SystemBarStyle.auto(Color.TRANSPARENT, Color.TRANSPARENT),
navigationBarStyle: SystemBarStyle = SystemBarStyle.auto(DefaultLightScrim, DefaultDarkScrim)
): Unit
Enables the edge-to-edge display for this ComponentActivity.
To set it up with the default style, call this method in your Activity's onCreate method:
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
...
}
The default style configures the system bars with a transparent background when contrast can be enforced by the system (API 29 or above). On older platforms (which only have 3-button/2-button navigation modes), an equivalent scrim is applied to ensure contrast with the system bars.
See SystemBarStyle for more customization options.
| Parameters | |
|---|---|
statusBarStyle: SystemBarStyle = SystemBarStyle.auto(Color.TRANSPARENT, Color.TRANSPARENT) |
The |
navigationBarStyle: SystemBarStyle = SystemBarStyle.auto(DefaultLightScrim, DefaultDarkScrim) |
The |