Created
July 2, 2024 10:51
-
-
Save rahat14/654708ec9faf94ecafe948ddfdcc63d5 to your computer and use it in GitHub Desktop.
Top Snackbar In compose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.Bundle | |
import androidx.activity.ComponentActivity | |
import androidx.activity.compose.setContent | |
import androidx.compose.foundation.layout.Box | |
import androidx.compose.foundation.layout.fillMaxSize | |
import androidx.compose.material3.* | |
import androidx.compose.runtime.* | |
import androidx.compose.ui.Alignment | |
import androidx.compose.ui.Modifier | |
import androidx.compose.ui.graphics.Color | |
import androidx.compose.ui.tooling.preview.Preview | |
import kotlinx.coroutines.launch | |
class MainActivity : ComponentActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContent { | |
SnackbarExample() | |
} | |
} | |
} | |
@Composable | |
fun SnackbarExample() { | |
val snackbarHostState = remember { SnackbarHostState() } | |
val coroutineScope = rememberCoroutineScope() | |
Box( | |
modifier = Modifier.fillMaxSize() | |
) { | |
Button( | |
onClick = { | |
coroutineScope.launch { | |
snackbarHostState.showSnackbar("This is a Snackbar") | |
} | |
}, | |
modifier = Modifier.align(Alignment.Center) | |
) { | |
Text("Show Snackbar") | |
} | |
SnackbarHost( | |
hostState = snackbarHostState, | |
snackbar = { snackbarData -> | |
Snackbar( | |
snackbarData, | |
modifier = Modifier | |
.align(Alignment.BottomStart) // Change this to your desired position | |
.padding(16.dp) | |
) | |
} | |
) | |
} | |
} | |
@Preview(showBackground = true) | |
@Composable | |
fun DefaultPreview() { | |
SnackbarExample() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment