【问题标题】:Compose Preview not working in Android Studio when using permissions (appcompanist)Compose Preview not working in Android Studio when using permissions (appcompanist)
【发布时间】:2022-12-27 10:36:12
【问题描述】:

When I add this line in my composable, the preview gives exception.

Code: val locationPermissionsState = rememberMultiplePermissionsState( listOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION ) )

Exception message is "This preview was unable to find a CompositionLocal, and the stack trace is

java.lang.IllegalStateException: Permissions should be called in the context of an Activity at com.google.accompanist.permissions.PermissionsUtilKt.findActivity(PermissionsUtil.kt:138) at com.google.accompanist.permissions.MutableMultiplePermissionsStateKt.rememberMutablePermissionsState(MutableMultiplePermissionsState.kt:80) at com.google.accompanist.permissions.MutableMultiplePermissionsStateKt.rememberMutableMultiplePermissionsState(MutableMultiplePermissionsState.kt:48) at com.google.accompanist.permissions.MultiplePermissionsStateKt.rememberMultiplePermissionsState(MultiplePermissionsState.kt:38)

【问题讨论】:

  • The app is working fine and exactly as it should, but just the preview in Android Studio doesn't work with this thing, which makes the development a little difficult. Thanks

标签: android kotlin android-jetpack-compose


【解决方案1】:

I was able to preview composable functions in Android Studio (Electric Eel) that use the MultiplePermissionsState interface by implementing the interface and hardcoding the necessary state for the preview.

Here is an example:

@ExperimentalPermissionsApi
class MultiplePermissionsStatePreview : MultiplePermissionsState {

    override val allPermissionsGranted: Boolean
        get() = false

    override val permissions: List<PermissionState>
        get() = emptyList()

    override val revokedPermissions: List<PermissionState>
        get() = emptyList()

    override val shouldShowRationale: Boolean
        get() = true

    override fun launchMultiplePermissionRequest() {
        // do nothing
    }
}

@ExperimentalPermissionsApi
@Preview
@Composable
private fun PermissionsPreview() {
    AppTheme {
        PermissionsScreen(
            multiplePermissionsState = MultiplePermissionsStatePreview()
            // ...
        )
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 2022-12-27
    • 2021-02-27
    • 2020-11-11
    • 2013-03-25
    • 2011-04-18
    • 2014-11-21
    相关资源
    最近更新 更多