× back

Android Menu

In Android, a menu is a collection of items that provide the user with specific actions. These actions can be global, context-specific, or related to particular views or components within the application. Menus help to organize the user interface and offer users ways to interact with the app's features efficiently.

Types of Android Menus:

  1. Options Menu

    The Options Menu is the primary menu that appears in the app's toolbar or action bar. It provides global actions such as "Settings", "Search", and other actions relevant throughout the app. It is accessed by tapping on the menu icon (three dots) in the toolbar.

  2. Context Menu

    The Context Menu appears when a user performs a long press on a specific view, such as a list item or button. It displays actions that are specific to the item being pressed, such as "Edit", "Delete", or "Share".

  3. Overflow Menu

    The Overflow Menu is part of the Options Menu and is accessed when there is not enough space in the toolbar to display all items. It is accessed by tapping the three vertical dots (overflow icon). This menu contains additional actions that can be accessed by the user when needed.

  4. Popup Menu

    The Popup Menu is a temporary menu that appears when a user interacts with a specific UI element, such as a button. It displays a list of items in a small window, providing context-specific actions related to that view or component.

PopupMenu

  • PopupMenu is a lightweight, easy-to-implement menu in Android that displays a small list of actions anchored to a particular view (like a Button).

Steps to Create a PopupMenu Demo Program:

  1. Add a Button:

    In activity_main.xml, add a Button that will act as the anchor point for the PopupMenu. Give it an ID and set its text to something like "Show Menu" for clarity.

    Example:

                                
    <Button
        android:id="@+id/showMenuButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Menu" />
                                
                            
  2. Create the Menu Resource File:

    The menu items to be displayed in the PopupMenu are defined in an XML file named main_menu.xml. Here’s how to create it:

    1. Create a Menu Folder:
      • Right-click on the res folder.
      • Select New > Android Resource Directory.
      • Set the Resource Type to menu, and click OK.
    2. Create a Menu File:
      • Right-click on the newly created menu folder.
      • Select New > Menu Resource File.
      • Name it main_menu.xml.

    In the main_menu.xml, define the menu items:

                                
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:id="@+id/menu_item1"
            android:title="Option 1" />
        <item
            android:id="@+id/menu_item2"
            android:title="Option 2" />
    </menu>
                                
                            

    Why Use main_menu.xml?

    • Separation of UI from Code: It keeps the UI structure separate from the logic, making it easier to update without modifying Java code.
    • Reusability: You can reuse the same menu file across multiple activities or fragments.
    • Customizability: Easily change icons, titles, or structure by editing the XML file, and the changes will automatically reflect in the UI.
  3. Handle Button Click to Show the PopupMenu:

    In the MainActivity.java file, write code to display the PopupMenu when the Button is clicked. This involves the following steps:

    1. Set an OnClickListener:

      Use buttonObj.setOnClickListener() to detect clicks on the Button. When clicked, execute the code to display the PopupMenu.

    2. Create a PopupMenu Object:

      Use the PopupMenu constructor, passing two parameters:

      • context: The activity where the menu is displayed (e.g., MainActivity.this).
      • anchor: The view to which the PopupMenu is attached (e.g., the Button).

      Example:

                                          
      PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);
                                          
                                      

      The anchor determines where the menu will appear (below or beside the Button).

    3. Inflate the Menu:

      Use popupMenu.inflate() to load the menu structure from the XML file:

                                          
      popupMenu.inflate(R.menu.main_menu);
                                          
                                      

      This links the menu resource file (main_menu.xml) to the PopupMenu.

    4. Show the PopupMenu:

      Call popupMenu.show() to display the menu:

                                          
      popupMenu.show();
              
                                      
    5. Handle Menu Item Clicks:

      Use popupMenu.setOnMenuItemClickListener() to handle what happens when a menu item is selected. Inside this, override onMenuItemClick() to define the actions for each item:

      1. onMenuItemClick(MenuItem item): This method detects which menu item was clicked.
      2. item.getItemId(): This function retrieves the unique ID of the clicked menu item. Use a switch or if to identify the clicked item and take appropriate actions.

      Example:

                                          popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
          @Override
          public boolean onMenuItemClick(MenuItem item) {
              switch (item.getItemId()) {
                  case R.id.menu_item1:
                      // Handle Option 1
                      return true;
                  case R.id.menu_item2:
                      // Handle Option 2
                      return true;
                  default:
                      return false;
              }
          }
      });
      
                                      

Program Example:

                            <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/popupMenuButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Menu"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />

</androidx.constraintlayout.widget.ConstraintLayout>
                            
                        
                            <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/home"
        android:title="Home"
        app:showAsAction="always"/>
    <item
        android:id="@+id/edit"
        android:title="Edit"
        app:showAsAction="always"/>
    <item
        android:id="@+id/exit"
        android:title="Exit"
        app:showAsAction="always"/>
</menu>
                            
                        
                            package com.example.myapplication;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {
    Button popupMenuButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        popupMenuButton = findViewById(R.id.popupMenuButton);
        popupMenuButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);
                popupMenu.inflate(R.menu.main_menu55);
                popupMenu.show();
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        int id = item.getItemId();
                        if(id == R.id.home)
                        {
                            Toast.makeText(MainActivity.this, "Home Selected", Toast.LENGTH_SHORT).show();
                        } else if(id == R.id.edit)
                        {
                            Toast.makeText(MainActivity.this, "Edit Selected", Toast.LENGTH_SHORT).show();
                        } else if(id == R.id.exit)
                        {
                            finish();
                        }
                        return true;
                    }
                });
            }
        });
    }
}
                            
                        

Context Menu

  • A Context Menu in Android is a menu that appears when you long-press or right-click on a view (like a Button).

Steps to Create a Context Menu Demo Program:

  1. Add a Button:

    In activity_main.xml, add a Button that will act as the anchor point for the Context Menu. Give it an ID and set its text to something like "Show Context Menu" for clarity.

    Example:

                                
    <Button
        android:id="@+id/showContextMenuButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Context Menu" />
                                
                            
  2. Register for Context Menu:

    In MainActivity.java, you need to register the Button for the context menu. This allows the Button to trigger the context menu when long-pressed.

    Function: registerForContextMenu(View view)

    Parameters:

    • view: The view (e.g., Button) on which the context menu should be shown when long-pressed.

    In your Java code:

                                
    registerForContextMenu(btn);
                                
                            

    This method links the Button (or any other view) to the context menu, making it respond to long-press actions.

  3. Create the Menu Resource File:

    The menu items for the Context Menu are defined in an XML file, typically named main_menu.xml.

    1. Create a Menu Folder:
      • Right-click on the res folder.
      • Select New > Android Resource Directory.
      • Set the Resource Type to menu, and click OK.
    2. Create a Menu File:
      • Right-click on the newly created menu folder.
      • Select New > Menu Resource File.
      • Name it main_menu.xml.

    In main_menu.xml, define the menu items:

                                
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:id="@+id/m1"
            android:title="Home" />
        <item
            android:id="@+id/m2"
            android:title="Edit" />
        <item
            android:id="@+id/m3"
            android:title="Close" />
    </menu>
                                
                            
  4. Override onCreateContextMenu:

    This function is called when the context menu is being created. It allows us to specify the structure of the context menu, such as the menu items.

    Function: onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)

    Parameters:

    • menu: The ContextMenu object in which the menu items will be added.
    • v: The view that was long-pressed (e.g., the Button). It helps identify the source of the menu.
    • menuInfo: Contains additional information about the context menu. It's typically used when dealing with specific views like ListViews.

    The getMenuInflater().inflate(R.menu.main_menu, menu) call inflates the main_menu.xml file into the context menu.

    Example:

                                
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }
                                
                            
  5. Override onContextItemSelected:

    This function is called when a menu item from the context menu is selected. It allows you to handle the user’s selection.

    Function: onContextItemSelected(MenuItem item)

    Parameters:

    • item: The menu item that was selected. You can use item.getItemId() to identify which menu item was chosen.

    This function returns true if the item selection was handled successfully. If not, return false.

    Example:

                                
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        int id = item.getItemId();
    
        if(id == R.id.m1) {
            Toast.makeText(this, "Home Selected", Toast.LENGTH_SHORT).show();
        } else if(id == R.id.m2) {
            Toast.makeText(this, "Edit Selected", Toast.LENGTH_SHORT).show();
        } else if(id == R.id.m3) {
            finish();
        }
        return super.onContextItemSelected(item);
    }
                                
                            

ContextMenu demo program:

                            <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/contextMenuButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Context Menu"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />

</androidx.constraintlayout.widget.ConstraintLayout>
                            
                        
                            <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/home"
        android:title="Home"
        app:showAsAction="always"/>
    <item
        android:id="@+id/edit"
        android:title="Edit"
        app:showAsAction="always"/>
    <item
        android:id="@+id/exit"
        android:title="Exit"
        app:showAsAction="always"/>
</menu>
                            
                        
                            package com.example.myapplication;

import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {
    Button contextMenuButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        contextMenuButton = findViewById(R.id.contextMenuButton);
        registerForContextMenu(contextMenuButton);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        super.onCreateContextMenu(menu, v, menuInfo);

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.home){
            Toast.makeText(this, "Home Selected", Toast.LENGTH_SHORT).show();
        } else if(id == R.id.edit)
        {
            Toast.makeText(this, "Edit Selected", Toast.LENGTH_SHORT).show();
        } else if(id == R.id.exit) finish();
        return super.onContextItemSelected(item);
    }
}
                            
                        

Options Menu

  • The Options Menu is the actual menu that is displayed within the Toolbar, and it contains items like "Search", "Settings", etc. The Toolbar simply provides a place to show this menu.
  • It offers more flexibility than the default ActionBar by providing additional customization options like adding menus, custom layouts, or styling.

Steps to Create a Toolbar with Options Menu:

  1. Include Toolbar in XML Layout:

    In the activity_main.xml layout file, you need to include the Toolbar element to define the top bar of your application. It can be positioned at the top of the screen and customized as needed.

    Example:

                                
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:titleTextColor="#FFFFFF" />
                                
                            

    Attributes:

    • android:id: The ID of the Toolbar, which is used to reference it in your Java code.
    • android:background: The background color of the Toolbar (can reference the app's theme color).
    • android:title: The title text shown in the center of the Toolbar.
    • android:titleTextColor: The color of the title text.
    • android:elevation: The shadow or elevation of the Toolbar, giving it a 3D effect.
  2. Set the Toolbar as ActionBar in Java:

    Once you have defined the Toolbar in XML, you need to set it as the ActionBar programmatically in your MainActivity.java (or any activity where you want the Toolbar). This replaces the default ActionBar with the custom Toolbar.

    Code Example:

                                
    // Toolbar - androidx.appcompat.widget wala
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
                                
                            

    Explanation: The method setSupportActionBar(toolbar) is used to set the Toolbar as the app's ActionBar, allowing you to use features like a title, menus, and navigation icons.

  3. Adding Menu to the Toolbar:

    You can add a menu to the Toolbar to provide users with additional options. To do this, you need to override the onCreateOptionsMenu() method in your activity.

    Steps:

    1. Create a Menu Resource File:

      First, create a menu XML file (e.g., toolbar_menu.xml) inside the res/menu/ folder:

                                          
      <menu xmlns:android="http://schemas.android.com/apk/res/android">
          <item
              android:id="@+id/action_search"
              android:title="Search"
              android:icon="@drawable/ic_search"
              android:showAsAction="ifRoom" />
          <item
              android:id="@+id/action_settings"
              android:title="Settings"
              android:showAsAction="never" />
      </menu>
                                          
                                      

      In this file:

      • android:id: The ID for each menu item.
      • android:title: The text that will be displayed for the menu item.
      • android:icon: The icon for the menu item (optional).
      • android:showAsAction: Determines whether the menu item should be shown in the action bar or overflow menu.
    2. Inflate the Menu in Activity:

      In the activity, override the onCreateOptionsMenu() method to load the menu and display it in the Toolbar:

                                          
      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
          getMenuInflater().inflate(R.menu.toolbar_menu, menu);
          return true;
      }
                                          
                                      

      This links the toolbar_menu.xml file to the Toolbar and populates it with the menu items.

  4. Handle Menu Item Clicks:

    Once you have added menu items to the Toolbar, you need to handle their clicks using the onOptionsItemSelected() method. This is where you define what happens when each menu item is clicked.

    Code Example:

                                
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_search) {
            Toast.makeText(this, "Search Clicked", Toast.LENGTH_SHORT).show();
            return true;
        } else if (id == R.id.action_settings) {
            Toast.makeText(this, "Settings Clicked", Toast.LENGTH_SHORT).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
                                
                            

    This method checks the ID of the clicked menu item and performs the corresponding action, such as showing a Toast message.

Demo Program:

                            
&tl;?xml version="1.0" encoding="utf-8"?>
&tl;androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    &tl;androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="409dp"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />
&tl;/androidx.constraintlayout.widget.ConstraintLayout>
                            
                        
                            <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/home"
        android:title="Home"
        app:showAsAction="always"/>
    <item
        android:id="@+id/edit"
        android:title="Edit"
        app:showAsAction="always"/>
    <item
        android:id="@+id/exit"
        android:title="Exit"
        app:showAsAction="always"/>
</menu>
                            
                        
                            package com.example.myapplication;

import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {
     Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.home) {
            Toast.makeText(this, "Home Clicked", Toast.LENGTH_SHORT).show();
            return true;
        } else if (id == R.id.edit) {
            Toast.makeText(this, "Edit Clicked", Toast.LENGTH_SHORT).show();
            return true;
        } else if(id == R.id.exit)
        {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}
                            
                        

Android Layouts

Layouts in Android define the structure and arrangement of views (UI components) in an application. They act as containers for UI elements, specifying their position and behavior on the screen. Layouts are written in XML and help in designing the user interface for different screen sizes and orientations.

Types of Layouts:

  1. LinearLayout:

    A layout that arranges its child views in a single row (horizontally) or column (vertically).

    • Use the android:orientation attribute to specify horizontal or vertical alignment.
    • Child views are displayed one after another in the specified direction.

    Example:

                    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Click Me" />
    
    </LinearLayout>
                    
                
  2. RelativeLayout:

    A layout where child views are positioned relative to each other or to the parent container.

    • Attributes like layout_below, layout_alignParentTop, and layout_toRightOf are used to specify relationships.
    • Allows for flexible placement of views without requiring nested layouts.

    Example:

                    
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Welcome!" />
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Click Me"
            android:layout_below="@id/textView" />
    
    </RelativeLayout>
                    
                
  3. ConstraintLayout:

    A flexible and efficient layout that positions child views using constraints relative to other views or guidelines.

    • Allows for creating complex designs with fewer nested layouts, improving performance.
    • Supports features like chains, barriers, and guidelines for precise alignment.

    Example:

                    
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent" />
    
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Click Me"
            app:layout_constraintTop_toBottomOf="@id/textView"
            app:layout_constraintStart_toStartOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
                    
                

Widgets

RadioButton

  • A RadioButton allows users to select one option from a group.
    • A RadioButton is a two-state widget, either checked (selected) or unchecked (unselected).
    • You can directly set its state programmatically using setChecked(true/false) or query it using isChecked().
  • It is typically used within a RadioGroup to ensure only one selection is allowed at a time.
    • A RadioGroup is a container for grouping multiple RadioButton widgets.
    • It enforces single selection, meaning only one RadioButton within the group can be selected at a time.
    • Selecting one RadioButton automatically deselects the previously selected one.

Important Functions

  • For RadioGroup:
    • getCheckedRadioButtonId(): Returns the ID of the currently selected RadioButton in the group. If no button is selected, it returns -1.
  • For RadioButton:
    • isChecked(): Returns true if the button is selected, false otherwise.
    • getText(): Returns the text associated with the RadioButton. Example: radioButton.getText().toString();

Program to demonstrate the use of RadioGroup and RadioButton

                            package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    // Declare views
    TextView tv;      // Displays the selected option or a message
    Button btn;       // Button to trigger the action
    RadioGroup rg;    // Group containing RadioButtons

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize views
        tv = findViewById(R.id.tv);
        btn = findViewById(R.id.button);
        rg = findViewById(R.id.radioGroup);

        // Set OnClickListener for the button
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Get the ID of the selected RadioButton
                int radioId = rg.getCheckedRadioButtonId();

                // Check if a RadioButton is selected
                if (radioId == -1) {
                    tv.setText("No Option is Selected"); // No selection
                } else {
                    // Find the selected RadioButton by ID
                    RadioButton rb = findViewById(radioId);
                    // Display the text of the selected RadioButton
                    tv.setText("Selected Option: " + rb.getText().toString());
                }
            }
        });
    }
}
                            
                        
                                <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="288dp"
        android:layout_height="127dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.088">

        <RadioButton
            android:id="@+id/radioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Red" />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Green" />
    </RadioGroup>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.471"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/radioGroup"
        app:layout_constraintVertical_bias="0.255" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>
                                
                            

CheckBox

  • A CheckBox is a two-state button that can be either checked (selected) or unchecked (unselected).
  • It is commonly used to allow users to make multiple selections from a list of options.
  • It supports independent selections, meaning multiple CheckBox widgets can be selected simultaneously.

Program to demonstrate the use of CheckBox

                                package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    // Declare views
    CheckBox cbReading, cbTraveling, cbGaming, cbCooking;
    Button btnSubmit;
    TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize views
        cbReading = findViewById(R.id.checkbox_reading);
        cbTraveling = findViewById(R.id.checkbox_traveling);
        cbGaming = findViewById(R.id.checkbox_gaming);
        cbCooking = findViewById(R.id.checkbox_cooking);
        btnSubmit = findViewById(R.id.button_submit);
        tvResult = findViewById(R.id.textView_result);

        // Set OnClickListener for the button
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String result = "Your hobbies are: ";

                // Check each checkbox and append the selected hobby
                if (cbReading.isChecked()) {
                    result += "Reading ";
                }
                if (cbTraveling.isChecked()) {
                    result += "Traveling ";
                }
                if (cbGaming.isChecked()) {
                    result += "Gaming ";
                }
                if (cbCooking.isChecked()) {
                    result += "Cooking ";
                }

                // Display result or fallback message
                if (result.equals("Your hobbies are: ")) {
                    tvResult.setText("No hobbies selected.");
                } else {
                    tvResult.setText(result);
                }
            }
        });
    }
}
                                
                            
                                <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <CheckBox
        android:id="@+id/checkbox_gaming"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="Gaming"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.516"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/checkbox_traveling" />

    <CheckBox
        android:id="@+id/checkbox_reading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="96dp"
        android:text="Reading"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.515"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="96dp"
        android:text="Submit"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.512"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/checkbox_cooking" />

    <CheckBox
        android:id="@+id/checkbox_traveling"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="Traveling"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.515"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/checkbox_reading" />

    <CheckBox
        android:id="@+id/checkbox_cooking"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="Cooking"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.515"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/checkbox_gaming" />

    <TextView
        android:id="@+id/textView_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        app:layout_constraintTop_toBottomOf="@id/button_submit"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
                                
                            

DatePicker

  • A DatePicker widget in Android allows users to select a specific date (day, month, year) via a calendar-like UI or spinner interface.
  • It can be embedded in a layout as a widget or displayed as a dialog.
  • It provides methods to retrieve or set the selected date programmatically.
  • We can't drag and drop a DatePicker like Buttons or TextViews because it is a complex widget with multiple dynamic components (such as day, month, and year spinners or calendar views). It requires specific attributes and configurations (e.g., datePickerMode, listeners) that need to be defined in the XML or programmatically, making it unsuitable for direct drag-and-drop placement in the design editor.

Key Methods:

  • getDayOfMonth(): Returns the currently selected day.
  • getMonth(): Returns the currently selected month (zero-based, so January = 0).
  • getYear(): Returns the currently selected year.
  • setOnDateChangedListener(): A listener that triggers whenever the user changes the date.

Example program

                                package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    DatePicker dp;
    TextView tv;

    @Override
    protected void onCreate(Bundle s) {
        super.onCreate(s);
        setContentView(R.layout.activity_main);

        // Initialize views
        dp = findViewById(R.id.datePicker);
        tv = findViewById(R.id.tv);

        // Set date change listener (only for Android O and above)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            dp.setOnDateChangedListener(new DatePicker.OnDateChangedListener() {
                @Override
                public void onDateChanged(DatePicker dp, int year, int monthOfYear, int dayOfMonth) {
                    int selectedMonth = dp.getMonth() + 1; // Convert zero-based month to 1-based
                    int selectedDay = dp.getDayOfMonth();
                    int selectedYear = dp.getYear();
                    tv.setText("Date = " + selectedDay + "/" + selectedMonth + "/" + selectedYear);
                }
            });
        }
    }
}
                                
                            
                                <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <DatePicker
        android:id="@+id/datePicker"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:datePickerMode="calendar" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.526"
        app:layout_constraintStart_toStartOf="@+id/datePicker"
        app:layout_constraintTop_toTopOf="@+id/datePicker"
        app:layout_constraintVertical_bias="0.733" />
</androidx.constraintlayout.widget.ConstraintLayout>
                                
                            

TimePicker

  • A TimePicker widget in Android allows users to select a specific time (hour and minute) via a spinner or clock interface.
  • It can be embedded in a layout as a widget or displayed as a dialog.
  • It provides methods to retrieve or set the selected time programmatically.
  • We can't drag and drop a TimePicker like Buttons or TextViews because it is a dynamic widget with multiple components (such as hours and minutes spinners or clock view). It requires specific attributes and configurations (e.g., timePickerMode, listeners), making it unsuitable for direct drag-and-drop placement in the design editor.

Key Methods:

  • getHour(): Returns the currently selected hour (in 24-hour format).
  • getMinute(): Returns the currently selected minute.
  • setOnTimeChangedListener(): A listener that triggers whenever the user changes the time.

Example program

                                package com.example.myapplication;

import android.os.Bundle;
import android.widget.TextView;
import android.widget.TimePicker;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    TimePicker timePicker;
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize views
        timePicker = findViewById(R.id.timePicker);
        tv = findViewById(R.id.tv);

        // Set listener to react to time changes
        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                // Use getter methods to fetch selected time
                int selectedHour = timePicker.getHour();
                int selectedMinute = timePicker.getMinute();
                tv.setText("Time Changed: " + selectedHour + ":" + selectedMinute);

                // Alternatively, you can use the listener's parameters:
                // tv.setText("Time Changed: " + hourOfDay + ":" + minute);
            }
        });
    }
}
                    
                
                                <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:timePickerMode="spinner" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/timePicker"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="16dp"
        android:textSize="18sp"
        android:text="Time will appear here" />
</androidx.constraintlayout.widget.ConstraintLayout>
                    
                

Alert Box

  • An Alert Box in Android is a simple dialog that shows a message to the user and optionally includes actions (e.g., OK, Cancel).
  • It is often used to display notifications, warnings, or confirmations.
  • An AlertDialog is the most common way to implement an alert box, and it can include a title, message, buttons, and custom layouts.

Example program

                                package com.example.myapplication;

import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    Button showAlertButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize button
        showAlertButton = findViewById(R.id.showAlertButton);

        // Set button click listener
        showAlertButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Alert Box Example")
                        .setMessage("This is a simple alert box.")
                        .setPositiveButton("OK", (d, w) -> {
                            // Action when OK button is clicked
                            Toast.makeText(MainActivity.this, "OK clicked!", Toast.LENGTH_SHORT).show();
                        })
                        .setNegativeButton("Cancel", (dialog, which) -> {
                            // Action when Cancel button is clicked
                            Toast.makeText(MainActivity.this, "Cancelled!", Toast.LENGTH_SHORT).show();
                        })
                        .show();
            }
        });
    }
}
                            
                        
                                <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/showAlertButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Alert"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
                            
                        

Progress Bar

  • A Progress Bar in Android is a visual indicator that shows the progress of a task or operation.
  • It can be indeterminate (spinning) or determinate (progressing through a defined range).
  • Indeterminate Progress Bars are used when the duration or progress of a task cannot be determined.
  • The visibility of a ProgressBar can be toggled programmatically to show or hide it during operations.

Example program

                                package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    ProgressBar pb;
    Button toggleButton;
    boolean var = false; // Initialize the variable to track visibility

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pb = findViewById(R.id.progressBar);
        toggleButton = findViewById(R.id.btnStartProgress);

        toggleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMe(v); // Call the method to toggle visibility
            }
        });
    }

    public void showMe(View view) {
        if (var) {
            pb.setVisibility(View.GONE); // Hide the progress bar
            var = false;
        } else {
            pb.setVisibility(View.VISIBLE); // Show the progress bar
            var = true;
        }
    }
}
                            
                        
                                <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnStartProgress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="264dp"
        android:text="Toggle Progress Bar"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/progressBar" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="59dp"
        android:layout_height="0dp"
        android:layout_marginTop="219dp"
        android:layout_marginBottom="161dp"
        android:visibility="gone"
        app:layout_constraintBottom_toTopOf="@+id/btnStartProgress"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>