Coding Bihar

Menu in Jetpack Compose

Menu in Jetpack Compose - Coding Bihar
Menu in Jetpack Compose

Menu in Jetpack Compose

What is Menu?
Menu is used to show a group of list on a temporary screen on a main screen. Users can select an option from a list. There are two types of menus we use in our app:
1. Dropdown menus - It show a list of options that user can select to perform an action. 
The different types of dropdown menus
Context menu - It is a floating menu when we press long click on a composable elements such as Button or Text a list of option will appear on the same screen.
Popup -It displays a list of items in a vertical list if we click a composable component.
2. Exposed dropdown menus - It displays a dropdown menu below a text field when a user click on it. At this time it is 
div>@OptIn(ExperimentalMaterial3Api::class)
Other alternative for menu is Navigation Drawer, Bottom Sheet and Navigation Rail.
Welcome to codingbihar.com. Today in this article we will learn to create a menu using jetpack compose. In this tutorial we are using the Android Studio the latest version. Menus are generally used to show a list of option for performing an action but we can also use it to navigate between screens but in this tutorial only create a menu with some options and if you want a menu to navigate then read the article on Navigation Drawer.
Steps to create a menu using jetpack compose
Step 1 - Create a New Project and select Empty Activity
Create a New Project and select Empty Activity
Step 2 - Name your application what you want in may case it is Compose Menu.
Menu in Jetpack Compose
Step 3 - MainActivity - Here is the code of Main Activity
Copy this code →

package com.example.composemenu
          
import...          
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeMenuTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    //DropdownMenuExample()
                    //PopupWindowDialog()
                    //MenuExample2()
                    //ExposedDropdownMenuExample()
                    MenuExample1()

                }
            }
        }
    }
}
Step 4 - ComposeMenu - Here is the code of Main Activity
Copy this code →

package com.example.composemenu

import...

@Composable
fun DropDownMenuExample() {
    var isExpanded by remember {
        mutableStateOf(false)
    }
   // var isButtonClicked by remember { mutableStateOf(false) }
    var textColor by remember { mutableStateOf(Color.Black) }

    Column (Modifier.padding(8.dp)) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentSize(Alignment.TopEnd)
        ) {
            IconButton(onClick = { isExpanded = !isExpanded }) {
                Icon(
                    imageVector = Icons.Default.MoreVert,
                    contentDescription = "More"
                )
            }
            DropdownMenu(expanded = isExpanded, onDismissRequest = { isExpanded = false }) {
                DropdownMenuItem(text = { Text(text = "Text in Red")},
                    onClick = { textColor= Color.Red })
                DropdownMenuItem(text = { Text(text = "Text in Blue") },
                    onClick = { textColor= Color.Blue })
                DropdownMenuItem(text = { Text(text = "Text in Magenta") },
                    onClick = { textColor= Color.Magenta })
                DropdownMenuItem(text = { Text(text = "Text in Cyan") },
                    onClick = { textColor= Color.Cyan })
                DropdownMenuItem(text = { Text(text = "Option 4") },
                    onClick = { /*TODO*/ })
                DropdownMenuItem(text = { Text(text = "Option 5") },
                    onClick = { /*TODO*/ })
                DropdownMenuItem(text = { Text(text = "Option 6") },
                    onClick = { /*TODO*/ })
            }
        }
        Text(text = stringResource(id = R.string.app_name),
            fontSize = 28.sp,
            fontWeight = FontWeight.ExtraBold)
        Text(text = stringResource(id = R.string.drop_down_menu), color = textColor)
        }
     }
OUTPUT: Here is the output of the code above for dropdown menu with some option using jetpack compose
dropdown menu using jetpack compose

Here is the code for exposed dropdown menu but at the time of writing it is Experimental Api.
Copy this code →

package com.example.composemenu

import...

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ExposedDropDownMenu1() {
    val context = LocalContext.current
    val options = arrayOf("Option 1", "Option 2", "Option 3", "Option 4", " Option 5")
    var expanded by remember { mutableStateOf(false) }
    var selectedOption by remember { mutableStateOf(options[0]) }

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(32.dp)
    ) {
        ExposedDropdownMenuBox(
            expanded = expanded,
            onExpandedChange = {
                expanded = !expanded
            }
        ) {
            TextField(
                value = selectedOption,
                onValueChange = {},
                readOnly = true,
                trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
                modifier = Modifier.menuAnchor()
            )

            ExposedDropdownMenu(
                expanded = expanded,
                onDismissRequest = { expanded = false }
            ) {
                options.forEach { item ->
                    DropdownMenuItem(
                        text = { Text(text = item) },
                        onClick = {
                            selectedOption = item
                            expanded = false
                            Toast.makeText(context, item, Toast.LENGTH_SHORT).show()
                        }
                    )
                }
            }
        }
    }
}
Output: Below is the output of the code above for exposed dropdown menu using jetpack compose

Menu in Jetpack Compose


Pop up Menu:Pop up menu is a type of menu which shows a pop up screen containing options to the user that can be selected to perform an action.
Copy this code →

package com.example.composemenu

import...
@Composable
fun PopUpMenuExample() {
    val openDialog = remember { mutableStateOf(false) }
    val buttonTitle = remember {
        mutableStateOf("Show Pop Up")
    }

    Column(

        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 20.dp),

        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {

        Button(

            modifier = Modifier
                .fillMaxWidth()
                .padding(10.dp),

            onClick = {

                openDialog.value = !openDialog.value


                if (!openDialog.value) {

                    buttonTitle.value = "Show Pop Up"
                }
            }
        ) {

            Text(
                text = buttonTitle.value,
                modifier = Modifier.padding(3.dp)
            )
        }

        Box {
            val popupWidth = 300.dp
            val popupHeight = 100.dp

            if (openDialog.value) {
                buttonTitle.value = "Hide Pop Up"
                Popup(
                    alignment = Alignment.TopCenter,
                    properties = PopupProperties()
                ) {
                    Box(
                        Modifier
                            .fillMaxSize()
                            //.size(popupWidth, popupHeight)
                            .padding(top = 5.dp)

                            .background(Color.Yellow, RoundedCornerShape(10.dp))

                            .border(1.dp, color = Color.Black, RoundedCornerShape(10.dp))
                    ) {


                        Column(

                            modifier = Modifier
                                .fillMaxSize()
                                .padding(horizontal = 20.dp),

                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Center
                        ) {

                            Text(
                                text = "PopUpMenuExample",
                                color = Color.Black,
                                modifier = Modifier.padding(vertical = 5.dp),
                                fontSize = 16.sp
                            )
                            Text(
                                text = "Option 1",
                                color = Color.Blue,
                                modifier = Modifier.padding(vertical = 5.dp),
                                fontSize = 16.sp
                            )
                            Text(
                                text = "Option 2",
                                color = Color.Blue,
                                modifier = Modifier.padding(vertical = 5.dp),
                                fontSize = 16.sp
                            )
                            Text(
                                text = "Option 3",
                                color = Color.Blue,
                                modifier = Modifier.padding(vertical = 5.dp),
                                fontSize = 16.sp
                            )
                            Text(
                                text = "Option 4",
                                color = Color.Blue,
                                modifier = Modifier.padding(vertical = 5.dp),
                                fontSize = 16.sp
                            )
                            Text(
                                text = "Option 5",
                                color = Color.Blue,
                                modifier = Modifier.padding(vertical = 5.dp),
                                fontSize = 16.sp
                            )
                        }
                    }
                }
            }
        }
    }
}
OUTPUT:
Menu in Jetpack Compose

Other alternative for menu is Navigation Drawer, null and Navigation Rail.
 Sandeep Gupta

Posted by Sandeep Gupta

Please share your feedback us at:sandeep@codingbihar.com. Thank you for being a part of our community!

Special Message

Welcome to coding bihar!