DialogFragment in Android
Last Updated :
06 Jun, 2024
Dialogs are a way to show more concise information or accessibility options without creating a new activity for users. This is quite useful when we have to show more options and stuff to the user and for that, we don’t want to create a whole new screen, we want the user to stay on the same screen and we want to show him a dialog which is floating on the previous screen. After that, We want to behave on the option selected from the dialog. Almost, in every good application, you will see the perfect usage of Dialog Box. From a user experience point of view also DialogFragment is a very good utility class of android development. In this article, we are going to know about the Introduction, Important methods, and implementation of DialogFragment in a real-world application.
What is DialogFragment?
DialogFragment is a utility class of android development that is used to show a Dialog window, Floating on top of an activity window in an android application. This feature is added on API Level 11 and Deprecated on API Level 28. It has its own lifecycle which makes this class very useful for dialog box creation. Here is a sample video to understand what we are going to build in this article and what actually a Dialog Fragment is-
Methods of DialogFragment
Below methods are given to control the flow of DialogFragment, with the proper usage of these methods dialog boxes can be controlled efficiently.
- onAttach()
- onCreate()
- onCreateDialog()
- onCreateView()
- onViewCreated()
- onDestroy()
Practical Implementation of DialogFragment
We will be implementing DialogFragment in a real-world android application. We will create a new project, if you are already working on any old project and wants to implement dialog fragment in that project you can do so also.
Step 1: Starting a new android studio project
- First of all start android studio
- On the main screen of android studio, you will see an option called Create a new project.
- Give a name of the project and fill all the other fields and click on next
- Also, select the empty activity and click on the finish
Step 2: Completing the pre-tasks for the application
Before we start developing our application we should perform some changes first. Now we have to do some changes to App Level Gradle file, For that go to Gradle Scripts > Build.gradle(Module:app) and import the following dependencies and click on Sync now.
implementation 'com.android.support:design:28.0.0'
Step 3: Working with activity_main.xml file-
The next step we have to follow is the user interface design for acitivity_main.xml, for that go-to app->res->Layout->activity_main.xml and then paste the below XML code.
XML
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/btnFragment"
android:layout_width="120dp"
android:layout_height="70dp"
android:text="Open Fragment"
android:layout_weight="1"
android:layout_margin="20dp"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Designing the UI For DialogFragment
The next step is to complete the design of our DialogFragment, for that go to res > layout > right-click > new > fragment file and name it as dialog_fragment.xml. Use the below code in it-
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="300dp"
android:layout_height="440dp"
android:background="#1D90EC"
app:circularflow_radiusInDP="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is Dialog Fragment"
android:textSize="40dp"
android:gravity="center"
android:textStyle="bold"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Step 5: Working with MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file.
Java
package com.example.dialogfragment;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button btnFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFragment=findViewById(R.id.btnFragment);
btnFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment dialogFragment=new DialogFragment();
dialogFragment.show(getSupportFragmentManager(),"My Fragment");
}
});
}
}
Step 6: Working with DialogFragment.java file
Extend this class with the DialogFragment method. Make an OnCreateView and Inside that use, inflater to inflate the UI of Dialog Box which is already created. Here is the all code for DialogFragment.java, you can paste it just after your package name.
Java
package com.example.dialogfragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class DialogFragment extends androidx.fragment.app.DialogFragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.dailog_fragment,container,false);
}
}
Output:
Here is the output of the application:
Similar Reads
How to set height equal to dynamic width (CSS fluid layout) ?
To create a fluid layout in CSS, set an element's height to the same value as its dynamic width. This makes the layout more adaptable and responsive since the element's height will automatically change depending on the viewport's width. It is possible to determine the element's height by using the p
2 min read
How to Set Height Equal to Dynamic Width (CSS fluid layout) in JavaScript ?
A key component of constructing a contemporary website in web development is developing an adaptable and dynamic layout. Setting the height of an element equal to its dynamic width, often known as a CSS fluid layout, is a common difficulty in accomplishing this. When the screen size changes and you
4 min read
How to Create Equal Height Columns in CSS ?
Equal Height Columns in CSS refer to ensuring that multiple columns in a layout have the same height, regardless of the content inside each column. This can be achieved using modern CSS techniques like Flexbox, CSS Grid, or the Table display property. Table of Content Using FlexUsing GridUsing Table
3 min read
How to make div height expand with its content using CSS ?
When designing a webpage, ensuring that a div adjusts its height according to its content is important for creating a flexible and responsive layout. By using CSS, you can easily make a div adapt to varying content sizes, which is particularly useful when dealing with dynamic or unpredictable conten
3 min read
How to Set Viewport Height & Width in CSS ?
Set viewport height and width in CSS is essential for creating responsive and visually appealing web designs. We'll explore the concepts of setting viewport height and width by using various methods like CSS Units, Viewport-Relative Units, and keyframe Media Queries. Table of Content Setting viewpor
3 min read
How to Stretch Elements to Fit the Whole Height of the Browser Window Using CSS?
To stretch elements to fit the whole height of the browser window using CSS, you can use "vh" units, where "1vh" equals 1% of the viewport height, so setting the height to "100vh" spans the entire height. Approach: Using CSS height PropertyIn this approach, we are using the Height property to fit th
1 min read
How to get the height of device screen in JavaScript ?
Given an HTML document which is running on a device. The task is to find the height of the working screen device using JavaScript. Prerequisite - How to get the width of device screen in JavaScript ? Example 1: This example uses window.innerHeight property to get the height of the device screen. The
2 min read
How to fit text container width dynamically according to screen size using CSS ?
In this article, we have given a text paragraph and the task is to fit the text width dynamically according to screen size using HTML and CSS. Some of the important properties used in the code are as follows- display-grid: It helps us to display the content on the page in the grid structure.grid-gap
7 min read
How to Adjust the Width and Height of an iframe to Fit the Content Inside It?
When using the <iframe> tag in HTML, the content inside the iframe is displayed with a default size if the width and height attributes are not specified. Even if the dimensions are specified, it can still be difficult to perfectly match the iframe’s size with the content inside it. This can be
4 min read
jQWidgets jqxLayout height Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxLayout is used for representing a jQuery widget that is used for the creation of complex layouts with nested
2 min read
How to Make Flexbox Items of Same Size Using CSS?
To make Flexbox items the same size using CSS, you can use various properties to control the dimensions of the items and ensure consistency in layout. By default, Flexbox items can have different sizes based on their content, but with a few CSS changes, you can make them uniform. 1. Using Flex Prope
5 min read
How to Specify Height to Fit-Content with Tailwind CSS ?
Specifying height to fit-content in Tailwind CSS means setting an element’s height to automatically adjust based on its content. Tailwind provides the h-fit utility class, which ensures the element's height dynamically adapts to its content's size. Adjusting Height with h-fit in Tailwind CSSThis app
2 min read
How to detect the change in DIV's dimension ?
The change in a div's dimension can be detected using 2 approaches: Method 1: Checking for changes using the ResizeObserver Interface The ResizeObserver Interface is used to report changes in dimensions of an element. The element to be tracked is first selected using jQuery. A ResizeObserver object
4 min read
How to Change the Height and Width of an Element with JavaScript?
To change the height and width of an element using JavaScript, you can directly manipulate the style property of the element. Here’s a simple guide on how to do it: Example:[GFGTABS] HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <m
1 min read
Primer CSS Layout width and height
Primer CSS is a free open-source CSS framework that is built with the GitHub design system to provide support to the broad spectrum of Github websites. It creates the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are ste
5 min read
How to Create Equal Width Table Cell Using CSS ?
Creating equal-width table cells using CSS refers to adjusting the table's layout so that all columns maintain the same width. This technique ensures a consistent and organized appearance, making the table content easier to read and visually balanced. Here we are following some common approaches: Ta
3 min read
How to Set Width and Height of Span Element using CSS ?
The <span> tag is used to apply styles or scripting to a specific part of text within a larger block of content. The <span> tag is an inline element, you may encounter scenarios where setting its width and height becomes necessary. This article explores various approaches to set the widt
2 min read
How to Set 100% Height with Padding/Margin in CSS ?
In this article, we'll explore CSS layouts with 100% width/height while accommodating padding and margins. In the process of web page design, it is often faced with scenarios where the intention is to have an element fill the entire width and/or height of its parent container, while also maintaining
3 min read
How to give a div tag 100% height of the browser window using CSS
CSS allows to adjustment of the height of an element using the height property. While there are several units to specify the height of an element. Set the height of a <div> to 100% of its parent container with height: 100%, or use height: 100vh; for a full viewport height, ensuring the <div
2 min read