How we can use bottom sheet in jetpack compose? - android

I am start to migrate my project to jetpack compose, and I am learning jetpack compose now, I want to use bottom sheet in my project, I search on internet to use bottom sheet, I find some codes, I use it in my app, every things looks good, but when I run the my app, it crashed, I am not sure where I mistake? Is there any other solution?
class MyActivity : ComponentActivity() {
#ExperimentalMaterialApi
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ModalBottomSheetLayoutScreen()
}
}
}
#OptIn(ExperimentalMaterialApi::class)
#Composable
fun ModalBottomSheetLayoutScreen() {
val modalBottomSheetState = rememberModalBottomSheetState(initialValue =
ModalBottomSheetValue.Hidden)
val scope = rememberCoroutineScope()
ModalBottomSheetLayout(
sheetContent = {
},
sheetState = modalBottomSheetState,
sheetShape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
sheetBackgroundColor = colorResource(id = R.color.white),
// scrimColor = Color.Red, // Color for the fade background when you open/close the drawer
) {
Scaffold(
backgroundColor = colorResource(id = R.color.white)
) {
MyScreen(scope = scope, state = modalBottomSheetState)
}
}
}
#OptIn(ExperimentalMaterialApi::class)
#Composable
fun MyScreen(
scope: CoroutineScope, state: ModalBottomSheetState
) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Column(
modifier = Modifier
.width(170.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "click",
modifier = Modifier
.clickable {
scope.launch {
state.show()
}
}
)}} }
#Preview(showBackground = true)
#Composable
fun ModalBottomSheetLayoutScreenPreview() {
ModalBottomSheetLayoutScreen()
}

It crashes because your sheetContent is empty. I've reported this bug. In a real app you should have some content, otherwise you don't need ModalBottomSheetLayout at all.
Specifying any view inside sheetContent solves the problem.

Related

Icon does not become invisible in jetpack compose

I have simple viewpager and toolbar in my code :
#Composable
fun DefaultAppBar(
mainViewModel: MainViewModel
) {
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl ) {
TopAppBar(
backgroundColor = Color.White
,
title = {
Text(text = "",
modifier = Modifier
.clickable { }
// margin
.padding(start = 160.dp)
)
},
actions = {
if(mainViewModel.searchWidgetVisibility.value) {
IconButton(
onClick = { },
modifier = Modifier,
) {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = "Search Icon",
tint = Color.Black,
modifier = Modifier,
)
}
}
}
)
}
}
As you can see above, I have an search icon which I want it to be visible whenever I enter SecondScreen in my viewpager .
MainViewModel.kt :
class MainViewModel:ViewModel() {
private val _searchWidgetVisibility: MutableState<Boolean> = mutableStateOf(value = false)
val searchWidgetVisibility: MutableState<Boolean> = _searchWidgetVisibility
fun updateSearchWidgetVisibility(newValue:Boolean) {
_searchWidgetVisibility.value = newValue
}
}
The searchWidgetVisibility controls the visibility of my search icon.
These are my pages in my viewpager :
#Composable
fun SecondScreen(
mainViewModel: MainViewModel
) {
mainViewModel.updateSearchWidgetVisibility(true)
Box(
modifier = Modifier
.fillMaxSize()
.background(color = C2)
,
contentAlignment = Alignment.Center
) {
Text(text = "second screen")
}
}
#Composable
fun FirstScreen(
mainViewModel: MainViewModel
) {
mainViewModel.updateSearchWidgetVisibility(false)
Box(
modifier = Modifier
.fillMaxSize()
.background(color = C2)
,
contentAlignment = Alignment.Center
) {
Text(text = "first screen")
}
}
But that does not work. when my search icon become visible for the first time,
when I navigate to the FirstScreen, It does not become invisible.
what is the problem here?
You need to place your mainViewModel.updateSearchWidgetVisibility(false) to not be called in your composition, Compose code needs to be side effect free. Because Composables can run at any time, in parallel or not at all. The position of where you are running that line of code, is not guaranteed to be executed at all.
More info here: https://developer.android.com/jetpack/compose/mental-model#parallel
If you need those functions to run when that composable is added to the composition, you should use LaunchedEffect to do so.
#Composable
fun FirstScreen(
mainViewModel: MainViewModel
) {
LaunchedEffect(mainViewModel) {
mainViewModel.updateSearchWidgetVisibility(false)
}
Box(
modifier = Modifier
.fillMaxSize()
.background(color = C2)
,
contentAlignment = Alignment.Center
) {
Text(text = "first screen")
}
}

Unable to show ModalBottomSheetLayout expanded

I'm having some issues with ModalBottomSheetLayout trying to make it fully expanded. I tried some answers from other posts (like Make ModalBottomSheetLayout always Expanded) with no result.
This is the Composable function I've created:
#OptIn(ExperimentalMaterialApi::class)
#Composable
fun ExpandedSheetDialog(
sheetContent: #Composable (() -> Unit),
screenContent: #Composable (() -> Unit),
modalState: ModalBottomSheetState
) {
ModalBottomSheetLayout(
sheetState = modalState,
sheetShape = RoundedCornerShape(topEnd = 10.dp, topStart = 10.dp),
sheetContent = { sheetContent.invoke() },
content = { screenContent.invoke() }
)
}
And this is the Preview:
#OptIn(ExperimentalMaterialApi::class)
#Preview(showBackground = true)
#Composable
fun ExpandedSheetDialogPreview() {
val scope: CoroutineScope = rememberCoroutineScope()
val modalSheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Expanded)
ExpandedSheetDialog(
sheetContent = {
Button(
onClick = {
scope.launch {
modalSheetState.animateTo(ModalBottomSheetValue.Hidden)
}
},
text = "Hide"
)
},
screenContent = {
Column(
modifier = Modifier.padding(16.dp).fillMaxHeight(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(
onClick = {
scope.launch {
modalSheetState.animateTo(ModalBottomSheetValue.Expanded)
}
},
text = "Show Extended"
)
}
},
modalState = modalSheetState
)
}
I tried in several emulators, all of them with the same result, the "BottomSheetDialog" appears but is not fully expanded. What am I doing wrong?

(Compose UI) - Keyboard (IME) overlaps content of app

A few days ago I bumped on a problem where a part of my view is overlaped by keyboard.
Let's say we have 3 different dialogs (could be any content), which looks like this:
When I want to write in anything, last dialog is covered by keyboard:
And there's no way to see what user wrote. Here's my code:
#Composable
fun BuildWordsView(navController: NavController, sharedViewModel: SharedViewModel) {
Column(
modifier = Modifier
.fillMaxWidth()
.background(PrimaryLight)
.fillMaxSize()
) {
BuildWordsScreenContents()
}
}
#Composable
fun BuildWordsScreenContents() {
Column(
Modifier
.fillMaxSize()
.padding(all = 16.dp)
) {
val inputBoxModifier = Modifier
.clip(RoundedCornerShape(10.dp))
.background(Primary)
.weight(12f)
.wrapContentHeight()
InputBlock("Dialog1", inputBoxModifier)
Spacer(Modifier.weight(1f))
InputBlock("Dialog2", inputBoxModifier)
Spacer(Modifier.weight(1f))
InputBlock("Dialog3", inputBoxModifier)
}
}
#Composable
fun InputBlock(dialogText: String, inputBlockModifier: Modifier) {
Column(modifier = inputBlockModifier) {
Text(
dialogText,
fontSize = 30.sp,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.Center)
)
var text by remember { mutableStateOf("") }
TextField(
value = text,
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.Center),
onValueChange = { text = it },
label = { Text("Label") }
)
}
}
This question seems to be similar to mine but answers modificate the content of view which I want to avoid:
Software keyboard overlaps content of jetpack compose view
By now I figured out how to solve this problem and I share my approach as an answer
My approach to deal with this problem is using Insets for Jetpack Compose:
https://google.github.io/accompanist/insets/
In order to start dealing with problem you need to add depency to gradle (current version is 0.22.0-rc).
dependencies {
implementation "com.google.accompanist:accompanist-insets:0.22.0-rc"
}
Then you need to wrap your content in your activity with ProvideWindowInsets
setContent {
ProvideWindowInsets {
YourTheme {
//YOUR CONTENT HERE
}
}
}
Additionaly you need to add following line in your activity onCreate() function:
WindowCompat.setDecorFitsSystemWindows(window, false)
Update: Despite this function is recommended, to my experience it may make this approach not work. If you face any problem, you may need to delete this line.
Now your project is set up to use Insets
In the next steps I'm gonna use code I provided in question
First of all you need to wrap your main Column with
ProvideWindowInsets(windowInsetsAnimationsEnabled = true)
Then let's modificate a modifier a bit by adding:
.statusBarsPadding()
.navigationBarsWithImePadding()
.verticalScroll(rememberScrollState())
As you can see the trick in my approach is to use verticalScroll(). Final code of main column should look like this:
#Composable
fun BuildWordsView(navController: NavController, sharedViewModel: SharedViewModel) {
ProvideWindowInsets(windowInsetsAnimationsEnabled = true) {
Column(
modifier = Modifier
.fillMaxWidth()
.background(PrimaryLight)
.statusBarsPadding()
.navigationBarsWithImePadding()
.verticalScroll(rememberScrollState())
.fillMaxSize()
) {
BuildWordsScreenContents()
}
}
}
Now let's modificate the modifier of Column in fun BuildWordsScreenContents()
The main modification is that we provide a height of our screen by:
.height(LocalConfiguration.current.screenHeightDp.dp)
This means that height of our Column would fit our screen perfectly. So when keyboard is not opened the Column will not be scrollable
There is the full code:
#Composable
fun BuildWordsView(navController: NavController, sharedViewModel: SharedViewModel) {
ProvideWindowInsets(windowInsetsAnimationsEnabled = true) {
Column(
modifier = Modifier
.fillMaxWidth()
.background(PrimaryLight)
.statusBarsPadding()
.navigationBarsWithImePadding()
.verticalScroll(rememberScrollState())
.fillMaxSize()
) {
BuildWordsScreenContents()
}
}
}
#Composable
fun BuildWordsScreenContents() {
Column(
Modifier
.height(LocalConfiguration.current.screenHeightDp.dp)
.padding(all = 16.dp)
) {
val inputBoxModifier = Modifier
.clip(RoundedCornerShape(10.dp))
.background(Primary)
.weight(12f)
.wrapContentHeight()
InputBlock("Dialog1", inputBoxModifier)
Spacer(Modifier.weight(1f))
InputBlock("Dialog2", inputBoxModifier)
Spacer(Modifier.weight(1f))
InputBlock("Dialog3", inputBoxModifier)
}
}
#Composable
fun InputBlock(dialogText: String, inputBlockModifier: Modifier) {
Column(modifier = inputBlockModifier) {
Text(
dialogText,
fontSize = 30.sp,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.Center)
)
var text by remember { mutableStateOf("") }
TextField(
value = text,
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.Center),
onValueChange = { text = it },
label = { Text("Label") }
)
}
}
The final code allows us to scroll down the view:
Important Note For APIs 30-
For APIs lower then 30 you need to modificate the AndroidManifest.xml file
In <activity you need to add android:windowSoftInputMode="adjustResize" in order to make it work. It do not resize your components but it is obligatory to make this approach work
Manifest should look like this:
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustResize"
Feel free to give me any tips how can I improve my question. AFAIK this problem is as old as android and I wanted to create a quick tutorial how to manage that. Happy coding!
Here's my solution, using the experimental features in Compose 1.2.0
In build.gradle (:project)
...
ext {
compose_version = '1.2.0-beta03'
}
...
In build.gradle (:app)
...
dependencies {
implementation 'androidx.core:core-ktx:1.8.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation "androidx.compose.foundation:foundation-layout:$compose_version"
...
}
In AndroidManifest.xml
<activity
...
android:windowSoftInputMode="adjustResize" >
In AuthScreen.kt
#OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class)
#Composable
fun AuthScreen(
val focusManager = LocalFocusManager.current
val coroutineScope = rememberCoroutineScope()
// Setup the handles to items to scroll to.
val bringIntoViewRequesters = mutableListOf(remember { BringIntoViewRequester() })
repeat(6) {
bringIntoViewRequesters += remember { BringIntoViewRequester() }
}
val buttonViewRequester = remember { BringIntoViewRequester() }
fun requestBringIntoView(focusState: FocusState, viewItem: Int) {
if (focusState.isFocused) {
coroutineScope.launch {
delay(200) // needed to allow keyboard to come up first.
if (viewItem >= 2) { // force to scroll to button for lower fields
buttonViewRequester.bringIntoView()
} else {
bringIntoViewRequesters[viewItem].bringIntoView()
}
}
}
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier
.fillMaxSize()
.statusBarsPadding()
.navigationBarsPadding()
.imePadding()
.padding(10.dp)
.verticalScroll(rememberScrollState())
) {
repeat(6) { viewItem ->
Row(
modifier = Modifier
.bringIntoViewRequester(bringIntoViewRequesters[viewItem]),
) {
TextField(
value = "",
onValueChange = {},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(
onNext = { focusManager.moveFocus(FocusDirection.Down) }),
modifier = Modifier
.onFocusEvent { focusState ->
requestBringIntoView(focusState, viewItem)
},
)
}
}
Button(
onClick = {},
modifier = Modifier
.bringIntoViewRequester(buttonViewRequester)
) {
Text(text = "I'm Visible")
}
}
}
Try to google into such keywords: Modifier.statusBarsPadding(), systemBarsPadding(), navigationBarsPadding().
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
makeStatusBarTransparent()
//WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
Box(
Modifier
.background(Color.Blue)
.fillMaxSize()
.padding(top = 10.dp, bottom = 10.dp)
.statusBarsPadding() //systemBarsPadding
) {
//Box(Modifier.background(Color.Green).navigationBarsPadding()) {
Greeting("TopStart", Alignment.TopStart)
Greeting("BottomStart", Alignment.BottomStart)
Greeting("TopEnd", Alignment.TopEnd)
Greeting("BottomEnd", Alignment.BottomEnd)
//}
}
}
/* setContent {
MyComposeApp1Theme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = Color.Red) {
Box(Modifier
.fillMaxSize()
.padding(top = 34.dp)
) {
Greeting("Android")
}
}
}
}*/
}
}
#Composable
fun Greeting(name: String, contentAlignment: Alignment) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = contentAlignment
) {
Text(
text = "Hello $name!",
Modifier
.background(color = Color.Cyan)
)
}
}
#Preview(showBackground = true)
#Composable
fun DefaultPreview() {
MyComposeApp1Theme {
Greeting("Android", Alignment.TopStart)
}
}
#Suppress("DEPRECATION")
fun Activity.makeStatusBarTransparent() {
window.apply {
clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
decorView.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
statusBarColor = android.graphics.Color.GREEN//android.graphics.Color.TRANSPARENT
}
}
val Int.dp
get() = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
toFloat(),
Resources.getSystem().displayMetrics
)

Why my bottomSheet comes from the top of screen in the jetpack compose

I have a bottomSheet but it comes from the top of the screen to the bottom when the screen is showing. How can I fix it?
This is my bottomSheet codes:
#ExperimentalMaterialApi
#Composable
fun BottomSheet(
modifier: Modifier = Modifier,
buttonText: String,
composable: #Composable () -> Unit,
scope: CoroutineScope
) {
val bottomSheetScaffoldState = rememberBottomSheetScaffoldState(
bottomSheetState = BottomSheetState(BottomSheetValue.Expanded)
)
BottomSheetScaffold(
scaffoldState = bottomSheetScaffoldState,
sheetContent = {
Column(
Modifier
.fillMaxWidth()
.height(200.dp)
.padding(8.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(colors = ButtonDefaults.buttonColors(
backgroundColor = AppColor.brandColor.BLUE_DE_FRANCE,
contentColor = AppColor.neutralColor.DOCTOR
),
shape = RoundedCornerShape(
small
),
onClick = {
scope.launch {
bottomSheetScaffoldState.bottomSheetState.collapse()
}
}) {
}
}
},
sheetPeekHeight = 0.dp,
sheetShape = RoundedCornerShape(topEnd = medium, topStart = medium)
) {
composable()
}
}
the composable function is a google map screen
My issue with this is only in the preview. When running it interactively or in the emulator it works fine. Maybe try this if you haven't already.

Model navigation drawer not covering statusbar. How to fix that?

I implemented a navigation drawer using jetpack compose. It looks like this
But it's not like the usual navigation drawer. it's not covering the status bar. I want this status bar like that one
here is my model navigation drawer code
#Composable
fun Drawer(scope: CoroutineScope, scaffoldState: ScaffoldState, navController: NavController) {
val items = listOf(
NavDrawerItem.Home,
NavDrawerItem.Music,
NavDrawerItem.Movies,
NavDrawerItem.Books,
NavDrawerItem.Profile,
NavDrawerItem.Settings
)
val item1 = "Logout"
Column(
modifier = Modifier
.background(colorResource(id = R.color.white))
.fillMaxSize()
) {
Image(
painter = painterResource(id = R.drawable.logo1),
contentDescription = R.drawable.logo1.toString(),
modifier = Modifier
.height(100.dp)
.fillMaxWidth()
.padding(10.dp)
)
Spacer(
modifier = Modifier
.fillMaxWidth()
.height(5.dp)
)
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
items.forEach { item ->
DrawerItem(item = item, selected = currentRoute == item.route, onItemClick = {
navController.navigate(item.route) {
navController.graph.startDestinationRoute?.let { route ->
popUpTo(route) {
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
scope.launch {
scaffoldState.drawerState.close()
}
})
}
Spacer(
modifier = Modifier
.fillMaxWidth()
.height(5.dp)
)
Logout(scope, scaffoldState)
Spacer(modifier = Modifier.weight(1f))
Text(
text = "Developed by CrazyBot Studio",
color = Color.Black,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(12.dp)
.align(Alignment.CenterHorizontally)
)
}
}
Is this possible on jetpack compose if yes the how can I do that?
You can check the Jetnews code:
In your Activity you can use something like:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
YourComposeTheme {
ProvideWindowInsets {
val systemUiController = rememberSystemUiController()
val darkIcons = MaterialTheme.colors.isLight
SideEffect {
systemUiController.setSystemBarsColor(Color.Transparent, darkIcons = darkIcons)
}
//SimpleScaffoldWithTopBar()
//Your Scaffold or Drawer code
}
}
}
Please try the below code in your Activity file.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
makeStatusBarTransparent()
}
private fun makeStatusBarTransparent() {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
I hope it works for you!!!

Categories

Resources