Kotlin Android Context MenuAndroid Context Menu is a floating menu which appears when a user performs a long-click on an element. The action performs on context menu affect only on the selected content. Context Menu can be implemented on any view, but it is mostly used with items of ListView, GridView or other view collections. Context Menu is created by overriding the onCreateContextMenu() function. The menu resource is inflated by and calling the inflate() method of MenuInflater class. To act on menu items, override the onContextItemSelected () function. Kotlin Android Context Menu ExampleIn this example, we will add a ListView and implements the context menu on its items. Performing the long-click on the list item shows the context menu items on which we can perform the relevant action. Create an android project and select the Basic Activity. This activity auto-generates codes for the menu option. activity_main.xmlAdd the following code in the activity_main.xml file in layout directory. This code is auto-generated while creating Basic Activity. content_main.xmlAdd the following code in the content_main.xml file in layout directory. In this file, we added a ListView. strings.xmlAdd the following code in the strings.xml file. menu_main.xmlAdd the following code in the menu_main.xml file in menu directory. Add the item tag which creates the menu item for the context menu. MainActivity.ktAdd the following code in the MianActivity.kt class. In this class, we create a list view and implement the context menu on its items. To add the list items for context menu the registerForContextMenu(list) method is used. To create the context menu override the onCreateContextMenu() and call the inflate() method of MenuInflater class. To perform action on each items of context menu override the onContextItemSelected() function.
Next Topic#
|