
- Android Basics
- Android - Home
- Android - Overview
- Android - Environment Setup
- Android - Architecture
- Android - Application Components
- Android - Hello World Example
- Android - Resources
- Android - Activities
- Android - Services
- Android - Broadcast Receivers
- Android - Content Providers
- Android - Fragments
- Android - Intents/Filters
- Android - User Interface
- Android - UI Layouts
- Android - UI Controls
- Android - Event Handling
- Android - Styles and Themes
- Android - Custom Components
- Android Advanced Concepts
- Android - Drag and Drop
- Android - Notifications
- Location Based Services
- Android - Sending Email
- Android - Sending SMS
- Android - Phone Calls
- Publishing Android Application
- Android Useful Examples
- Android - Alert Dialoges
- Android - Animations
- Android - Audio Capture
- Android - AudioManager
- Android - Auto Complete
- Android - Best Practices
- Android - Bluetooth
- Android - Camera
- Android - Clipboard
- Android - Custom Fonts
- Android - Data Backup
- Android - Developer Tools
- Android - Emulator
- Android - Facebook Integration
- Android - Gestures
- Android - Google Maps
- Android - Image Effects
- Android - ImageSwitcher
- Android - Internal Storage
- Android - JetPlayer
- Android - JSON Parser
- Android - Linkedin Integration
- Android - Loading Spinner
- Android - Localization
- Android - Login Screen
- Android - MediaPlayer
- Android - Multitouch
- Android - Navigation
- Android - Network Connection
- Android - NFC Guide
- Android - PHP/MySQL
- Android - Progress Circle
- Android - ProgressBar
- Android - Push Notification
- Android - RenderScript
- Android - RSS Reader
- Android - Screen Cast
- Android - SDK Manager
- Android - Sensors
- Android - Session Management
- Android - Shared Preferences
- Android - SIP Protocol
- Android - Spelling Checker
- Android - SQLite Database
- Android - Support Library
- Android - Testing
- Android - Text to Speech
- Android - TextureView
- Android - Twitter Integration
- Android - UI Design
- Android - UI Patterns
- Android - UI Testing
- Android - WebView Layout
- Android - Wi-Fi
- Android - Widgets
- Android - XML Parsers
- Android Useful Resources
- Android - Questions and Answers
- Android - Useful Resources
- Android - Discussion
Context Menu in Android with Example
What is the Context menu in Android?
In this tutorial, we are going to learn on How to display context menu in our android application using Kotlin as a programming language.
What is the context menu in android ?
Context menu is a short floating menu option which appears when the user long presses on a specific widget on the mobile application. This menu is just like a right click option in windows which is used to perform some quick actions within an android application for a specific widget.
Implementation of Context Menu
We will be creating a simple application for displaying a context menu in an android application. We will be following a step by step guide to implement a context menu in an android application.
Step 1 : Creating a new project in Android Studio
Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.
After clicking on New Project you will get to see the below screen.
Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.
Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.
Note − Make sure to select the Language as Kotlin.
After specifying all the details click on Finish to create a new Android studio project.
Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.kt file.
Step 2 : Working with activity_main.xml
Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- creating text view for displaying heading--> <TextView android:id="@+id/idTVHeading" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@id/idTVMessage" android:layout_marginStart="20dp" android:layout_marginTop="20dp" android:layout_marginEnd="20dp" android:layout_marginBottom="20dp" android:gravity="center" android:text="Context Menu in Android" android:textAlignment="center" android:textAllCaps="false" android:textColor="#FF000000" android:textSize="20sp" android:textStyle="bold" /> <!-- text view for displaying the selected menu item--> <TextView android:id="@+id/idTVMessage" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="20dp" android:gravity="center" android:text="Message" android:textAlignment="center" android:textAllCaps="false" android:textColor="#FF000000" android:textSize="20sp" android:textStyle="bold" /> </RelativeLayout>
Explanation − In the above code the root element is a Relative layout in android. This layout is a view group which is use to align all the elements within it relative to each other. We can relatively align all elements within Relative Layout with the help of ids or positions.
Inside this relative layout the first view which we have created is Text View. It is used to display a simple text message. Inside this text view widget we have specified its width as match_parent so that it will take the complete width of the mobile device and height as wrap content to take the text height.We are specifying id for our text view which is a unique identifier for that widget. We can use this id to perform some operations of this text view such as overriding a new text to it. After that we have added the layout center in parent. The parameter will align the text view widget to the center of the screen. After that we have added a parameter as gravity which again aligns the text inside the text view widget centrally.After that we are adding a text as a parameter inside which we will be specifying the value which we have to show inside our Text View. After specifying text we are specifying the text alignment. This will align the text inside the text view widget to the center of the widget. After that we are specifying text all caps which will add the same formatting to the text as we will specify while giving value inside our text. After that we are specifying the color for our text in our project. Lastly we are specifying the text size and adding a style for our text as bold.
After this text view we are creating one more text view in which we will be displaying the menu option which is selected by the user from the context menu.
At last we are adding a closing tag for our Relative Layout as the text view and button is enclosed in our relative layout.
Step 3 : Working with MainActivity.kt
Navigate to MainActivity.kt. If this file is not visible. To open this file. In the left pane navigate to app>java>your app’s package name>MainActivity.kt to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.
package com.example.gptapp import android.os.Bundle import android.view.ContextMenu import android.view.MenuItem import android.view.View import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // creating variables for video view on below line. lateinit var messageTV: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // initializing variable for video view on below line. messageTV = findViewById(R.id.idTVMessage) // registering context menu on below line. registerForContextMenu(messageTV) } override fun onCreateContextMenu( menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo? ) { super.onCreateContextMenu(menu, v, menuInfo) // on below line we are setting header title for menu. menu!!.setHeaderTitle("Choose Programming Language") // on below line we are adding menu items menu.add(0, v!!.getId(), 0, "Java") menu.add(0, v!!.getId(), 0, "Kotlin") menu.add(0, v!!.getId(), 0, "Dart") } override fun onContextItemSelected(item: MenuItem): Boolean { // on below line we are setting the selected item text for message text view messageTV.text = item.title return true } }
Explanation − In the above code for the MainActivity.kt file. Firstly we are creating a variable for the text view in which we will be displaying the item selected from context menu.
After creating variables we are initializing our text view variable named as messageTV with its unique id which we have given in the activity_main.xml file.
After initializing our text view we are registering for the context menu on our text view. We are passing the message text view to it because we have to display the context menu on our message text view.
Now we will be creating one more method named as onCreateContextMenu which is used for creating our menu. Inside this method we will be firstly setting the title for our menu using setHeaderTitle method then we will be adding menu items to it using add method. Inside this method we will be adding the items which we have to display inside our context menu.
Then we will be creating one more method named onContextItemSelected. This method is used when the user clicks any of the context items selected by the user. Inside this method we will be simply setting the text for our message text view as the title of our item and simply returning it to true.
After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.
Note − Make sure you are connected to your real device or emulator.
Conclusion
In the above tutorial we learn What is the context menu in android and how we can use it to display a short menu within our android application. We learned How to create this context menu in our android application and use it to display a floating menu option inside our application.
- Related Articles
- Android Popup Menu Example
- How to use Singleton with Global Context in android?
- AdapterViewFlipper in Android with Example
- Bundle in Android with Example
- How to store array Singleton with Global Context in android?
- How to add context menu to an image in JavaFX?
- Difference between Android Activity Context and Application Context
- Android ListView in Java with Example
- Absolute Layout in Android with Example
- Content Providers in Android with Example
- How to store JSON Object Singleton with Global Context in android?
- Execute a script when a context menu is triggered in HTML5?
- How to create a context menu for an element in HTML5?
- Fragment Tutorial with Example in Android Studio?
- Auto Image Slider in Android with Example
