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:
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.
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".
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.
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.
Steps to Create a PopupMenu Demo Program:
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" />
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:
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
?
In the MainActivity.java
file, write code to display the PopupMenu when the
Button is clicked. This involves the following steps:
Use buttonObj.setOnClickListener() to detect clicks on the Button. When clicked, execute the code to display the PopupMenu.
Use the PopupMenu constructor, passing two parameters:
Example:
PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);
The anchor determines where the menu will appear (below or beside the Button).
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.
Call popupMenu.show()
to display the menu:
popupMenu.show();
Use popupMenu.setOnMenuItemClickListener() to handle what happens when a menu item is selected. Inside this, override onMenuItemClick() to define the actions for each item:
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;
}
});
}
});
}
}
Steps to Create a Context Menu Demo Program:
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" />
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:
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.
The menu items for the Context Menu are defined in an XML file, typically named 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>
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:
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);
}
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:
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);
}
}
Steps to Create a Toolbar with Options Menu:
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:
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.
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:
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:
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.
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);
}
}
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:
A layout that arranges its child views in a single row (horizontally) or column (vertically).
android:orientation
attribute to specify horizontal or vertical
alignment.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>
A layout where child views are positioned relative to each other or to the parent container.
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>
A flexible and efficient layout that positions child views using constraints relative to other views or guidelines.
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>
Important Functions
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>
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>
Key Methods:
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>
Key Methods:
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>
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>
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>