DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • How To Optimize and Reduce Android Apps Size in Xamarin
  • How To Create a Homescreen Widget in Android
  • How Does WebView Actually Work on Android?
  • How To Integrate Chatbot With an Android App

Trending

  • Documenting a Spring REST API Using Smart-doc
  • How To Use Thread.sleep() in Selenium
  • Application Telemetry: Different Objectives for Developers and Product Managers
  • The Role of AI in Low- and No-Code Development
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. AlertDialog and DialogFragment Example in Xamarin Android

AlertDialog and DialogFragment Example in Xamarin Android

Dialog is like any other window that pops up in front of current window, used to show some short message, taking user input or to ask user decisions.

By 
Nilanchala Panigrahy user avatar
Nilanchala Panigrahy
·
Jul. 14, 15 · Tutorial
Like (0)
Save
Tweet
Share
32.2K Views

Join the DZone community and get the full member experience.

Join For Free

Dialog is like any other window that pops up in front of current window, used to show some short message, taking user input or to ask user decisions. Unlike Toast, a dialog is generally used where user attention is mandate. Android supports several different ways to create a dialog such as AlertDialog and FragmentDialog. In this example we will cover all the aspect of AlertDialog and DialogFragment.

1. Using AlertDialog in Xamarin.Android

AlertDialog is the subclass of Dialog that can display one, two or three buttons. If you only want to display a String in this dialog box, use the SetMessage() method.

The following code snippet can be used to create a simple AlertDialog with two buttons Delete and Cancel.

//set alert for executing the task
AlertDialog.Builder alert = new AlertDialog.Builder (this);
alert.SetTitle ("Confirm delete");
alert.SetMessage ("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.");
alert.SetPositiveButton ("Delete", (senderAlert, args) => {
Toast.MakeText(this ,"Deleted!" , ToastLength.Short).Show();
});

alert.SetNegativeButton ("Cancel", (senderAlert, args) => {
Toast.MakeText(this ,"Cancelled!" , ToastLength.Short).Show();
});

Dialog dialog = alert.Create();
dialog.Show();


The above code snippet will produce the output as shown in the following screenshot.

2. Using DialogFragment in Xamarin.Android

Since the release of Android 3.0 (API level 11), fragments can show as a dialogue and call as DialogFragment. If you’re supporting older Android versions, you can make use of the fragment-compatibility support library.

To create a dialogue fragment, we will be using DialogFragment class. This class is derived from the Fragment and behaves much like a fragment with all available fragment life cycle methods. Android recommends using DialogFragment over AlerDialog.

You need to perform the following steps to create a DialogFragment

  • Create a new class that extends from DialogFragment class.
  • Like regular Fragments, override OnCreateView() callback to attach the dialog layout.
  • Alternatively, you can override OnCreateDialog() the method and return a Dialog instance. This method is used to port your old AlertDialog code without much modification.

In this example, we will see both OnCreateView() and OnCreateDialog() callback.

3. Dialog fragment using OnCreateDialog()

The following code snippet shows how to create dialog by overriding OnCreateDialog() method.

C#
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;

namespace DialogExample
{
    public class DialogFragment2 : DialogFragment
    {
        public static DialogFragment2 NewInstance(Bundle bundle){
            DialogFragment2 fragment = new DialogFragment2 ();
            fragment.Arguments = bundle;
            return fragment;
        }
    
        public override Dialog OnCreateDialog (Bundle savedInstanceState)
        {
            AlertDialog.Builder alert = new AlertDialog.Builder (Activity);
            alert.SetTitle ("Confirm delete");
            alert.SetMessage ("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.");
            alert.SetPositiveButton ("Delete", (senderAlert, args) => {
                Toast.MakeText(Activity ,"Deleted!" , ToastLength.Short).Show();
            });
    
            alert.SetNegativeButton ("Cancel", (senderAlert, args) => {
                Toast.MakeText(Activity ,"Cancelled!" , ToastLength.Short).Show();
            });
    
            return alert.Create();
        }
    }
}


4. Dialog fragment using OnCreateView()

DialogFragment is like any other fragment, the same lifecycle rules are applied. Now we have to override onCreateView method to attach the layout to view the hierarchy and construct the dialogue fragment.

Let us first define the layout for your fragment. In this example, I have used two TextViews and Button. My layout looks as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">
    <TextView
        android:text="Lorem ipsum"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <TextView
        android:text="Lorem ipsum dolor sit amet, consectetuer adipiscing elit...."
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:layout_marginTop="10dp" />
    <Button
        android:text="Close"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/CloseButton"
        android:layout_marginTop="10dp" />
</LinearLayout>


Now let us inflate the layout from OnCreateView() method. My DialogFragment class looks as follows:

C#
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;

namespace DialogExample
{
    public class DialogFragment1 : DialogFragment
    {
        public static DialogFragment1 NewInstance(Bundle bundle){
            DialogFragment1 fragment = new DialogFragment1 ();
            fragment.Arguments = bundle;
            return fragment;
        }

        public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            View view =  inflater.Inflate(Resource.Layout.DialogFragment1Layout, container, false);
            Button button = view.FindViewById<Button> (Resource.Id.CloseButton);
            button.Click += delegate {
                Dismiss();
                Toast.MakeText(Activity ,"Dialog fragment dismissed!" , ToastLength.Short).Show();
            };
    
            return view;
        }
    }
}


The above code snippet will produce the output as shown in the following screenshot.


5. Adding DialogFragment

We are pretty much done! Add the following code snippet in your Activity to instantiate and display the dialog;

FragmentTransaction ft = FragmentManager.BeginTransaction();
//Remove fragment else it will crash as it is already added to backstack
Fragment prev = FragmentManager.FindFragmentByTag("dialog");
if (prev != null) {
    ft.Remove(prev);
}

ft.AddToBackStack(null);

// Create and show the dialog.
DialogFragment1 newFragment = DialogFragment1.NewInstance(null);

//Add fragment
newFragment.Show(ft, "dialog");
Android (robot) Dialog (software) Fragment (logic) xamarin

Published at DZone with permission of Nilanchala Panigrahy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Optimize and Reduce Android Apps Size in Xamarin
  • How To Create a Homescreen Widget in Android
  • How Does WebView Actually Work on Android?
  • How To Integrate Chatbot With an Android App

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: