How to get Activity's Label in Jetpack Compose?

Viewed 169

In AndroidManifest.xml, we need to declare our Activity and we can provide a label, i.e.

<activity android:name="MyActivityClass"
            android:label="Activity Label" />

In Jetpack Compose, how can I get that Activity Label?

I tried to get from LocalContext.current but can't find it.

@Composable
fun TopBar() {
    val context = LocalContext.current
    val title = context.getActivity().getTitle() // Wrong API... not there
    TopAppBar(
        title = { Text(text = title, fontSize = 18.sp) },
        backgroundColor = MaterialTheme.colors.primary,
        contentColor = Color.White
    )
}


2 Answers

The label provided for an Activity in the AndroidManifest.xml can be accessed in general through PackageManager.getActivityInfo(...).

Since you are using Compose anyway, here is a Kotlin flavoured extension function

inline fun <reified T> Context.getActivityLabel(): String {
    val componentName = ComponentName(this, T::class.java)
    val activityInfo = packageManager.getActivityInfo(componentName, 0)
    // loadLabel takes care of cases when the label is specified as a String literal 
    // as well as cases when the label is specified as a String resource
    return activityInfo.loadLabel(packageManager).toString()
}

Usage inside a Composable

val context = LocalContext.current
val title = context.getActivityLabel<MyActivityClass>()

Usage elsewhere

val context: Context = //...
val title = context.getActivityLabel<MyActivityClass>()

I got it through the below approach

@Composable
fun TopBar() {
    val activity = LocalContext.current as Activity
    val title = activity.title?.toString() ?: "No Title"
    TopAppBar(
        title = { Text(text = title, fontSize = 18.sp) },
        backgroundColor = MaterialTheme.colors.primary,
        contentColor = Color.White
    )
}

Related