What is Toolbar?
A Toolbar in Android is an element present on the top of the application screen which generally displays the application name. This is also known as action bar or app bar. In Jetpack Compose we don't get any default app bar so in this post we will create a collapsing toolbar.
What is Collapsing Toolbar?
Collapsing Toolbar is a toolbar that collapses when the application is scrolled down and holds up when scrolled up to the top. Collapsing toolbar is used with top app bar there are 4 types of top app bar is provided by Material Design Components. We can use one of them .
Top App Bar
- Top App Bar
- Centered Aligned Top App Bar
- Medium Top App Bar
- Large Top App Bar
Also Read How to create Divider in Jetpack Compose
How to build Collapsing Toolbar using jetpack compose
Steps:
Create a new project by selecting jetpack compose you have a file named MainActivity use the following code
MainActivity
package com.example.collapsingtoolbarcompose
import ...
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CollapsingToolbarComposeTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Collapsing()
}
}
}
}
}
Create a new file named as Collapsing Toolbar
We create a composable function named collapsing. You can use the following code and run you will get the output. we have content text named as content in the string xml file which you can find in the values.
Collapsing Toolbar :
package com.example.collapsingtoolbarcompose
import...
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Collapsing() {
val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
MediumTopAppBar(
title = { Text(
// color = Color.Red,
text = "Collapsing Tool Bar") },
navigationIcon = {
IconButton(onClick = { /*TODO*/ }) {
Icon(imageVector = Icons.Default.Menu, contentDescription = "")
}
},
scrollBehavior = scrollBehavior
)
},
content =
{ innerPadding ->
Column(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp)
.padding(innerPadding)
.verticalScroll(rememberScrollState())
) {
Text(
modifier = Modifier.padding(8.dp),
text = stringResource(id = R.string.contents)
)
}
}
)
}