简体   繁体   English

如何在 Jetpack Compose 中获取 Activity 的标签?

[英]How to get Activity's Label in Jetpack Compose?

In AndroidManifest.xml, we need to declare our Activity and we can provide a label, ie在AndroidManifest.xml中,我们需要声明我们的Activity,我们可以提供一个标签,即

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

In Jetpack Compose, how can I get that Activity Label?在 Jetpack Compose 中,如何获取该活动标签?

I tried to get from LocalContext.current but can't find it.我试图从LocalContext.current获取但找不到。

@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
    )
}


The label provided for an Activity in the AndroidManifest.xml can be accessed in general through PackageManager.getActivityInfo(...) .为 AndroidManifest.xml 中的 Activity 提供的标签通常可以通过PackageManager.getActivityInfo(...)访问。

Since you are using Compose anyway, here is a Kotlin flavoured extension function由于您无论如何都在使用 Compose,所以这里有一个 Kotlin 风格的扩展函数

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在 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
    )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM