only52607 / compose-floating-window

Library for creating global floating windows based on jetpack compose on Android.
Apache License 2.0
56 stars 8 forks source link
android compose floating-window jetpack-compose kotlin windowmanager windows

compose-floating-window

Release License

Global Floating Window Framework based on Jetpack Compose

简体中文

Preview

Preview

Features

Basic Usage

Import Dependencies

repositories {
    maven { url 'https://jitpack.io' }
}

Grant Floating Window Permission

Add to AndroidManifest.xml

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

Create Floating Window and Show

val floatingWindow = ComposeFloatingWindow(applicationContext)
floatingWindow.setContent {
    FloatingActionButton(
        modifier = Modifier.dragFloatingWindow(),
        onClick = {
            Log.i("")
        }) {
        Icon(Icons.Filled.Call, "Call")
    }
}
floatingWindow.show()

See Sample App.

Advanced Usage

Make Floating Window Draggable

Use the Modifier.dragFloatingWindow() modifier on the component you want to make draggable. Example:

FloatingActionButton(
    modifier = Modifier.dragFloatingWindow()
) {
    Icon(Icons.Filled.Call, "Call")
}

Get the current instance of ComposeFloatingWindow

Using LocalComposeFloatingWindow to retrieve, here's an example:

val floatingWindow = LocalComposeFloatingWindow.current

Show Dialog

When the Context of the floating window is set to Application, using AlertDialog and Dialog in the Compose interface of the floating window may result in a 'token is null' exception. In such cases, you can use the SystemAlertDialog or SystemDialog components, which can be used in the same way as the built-in AlertDialog and Dialog components.

Example:

SystemAlertDialog(
    onDismissRequest = { showDialog = false },
    confirmButton = {
        TextButton(onClick = { showDialog = false }) {
            Text(text = "OK")
        }
    },
    text = {
        Text(text = "This is a system dialog")
    }
)

ViewModel

You can access the ViewModel from any Composable by calling the viewModel() function.

class MyViewModel : ViewModel() { /*...*/ }

@Composable
fun MyScreen(
    viewModel: MyViewModel = viewModel()
) {
    // use viewModel here
}

See https://developer.android.com/jetpack/compose/libraries#viewmodel

License

Apache 2.0 License