A DialogFragment is a fragment that displays a dialog window, floating on top of its activity’s window.

This fragment contains a Dialog object, which it displays as appropriate based on the fragment’s state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.

We do inherit from this class(android.support.v4.app.DialogFragment) then implement the Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle) to supply the content of the dialogfragment.

You can also override onCreateDialog(Bundle) to create an entirely custom dialog, such as an AlertDialog, with its own content.

Let’s now look at some android dialog fragment examples:

Example 1 : Android DialogFragment – Show RecyclerView

This example will show a recyclerview in diaogfragment.

When the user clicks a show button we open a dialogfragment, displaying a RecyclerView on it.

Project Summary

No. File Major Responsibility
1. MyHolder.java RecyclerView ViewHolder class.
2. MyAdapter.java RecyclerView data adapter class
3. TVShowFragment.java DialogFragment class
4. MainActivity.java Activity class
5. activity_layout.xml To be inflated to MainActivity
6. content_main.xml To be included inside the activity_main.xml.We add our veiws and widgets here.
7. fraglayout.xml The layout to be inflated to our custom dialog fragment.
8. model.xml To model how each recyclerview item will appear

1. Create Basic Activity Project

  1. First create an empty project in android studio. Go to File –> New Project.
  2. Type the application name and choose the company name.
    New Project Dialog
  3. Choose minimum SDK.
    Choose minimum SDK
  4. Choose Basic activity.
    Choose Empty Activity
  5. Click Finish.
    Finish

Basic activity will have a toolbar and floating action button already added in the layout

Normally two layouts get generated with this option:

No. Name Type Description
1. activity_main.xml XML Layout Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton.
2. content_main.xml XML Layout Will be included into activity_main.xml.You add your views and widgets here.
3. MainActivity.java Class Main Activity.

In this example I used a basic activity.

The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.

If you’ve created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:


        <activity android_name=".MainActivity">

            <intent-filter>

                <action android_name="android.intent.action.MAIN" />

                <category android_name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

Advantage of Creating Basic Activity project

You can optionally choose empty activity over basic activity for this project.

However basic activity has the following advantages:

No. Advantage
1. Provides us a readymade toolbar which gives us actionbar features yet easily customizable
2. Provides us with appbar layout which implements material design appbar concepts.
3. Provides a FloatinActionButton which we can readily use to initiate quick actions especially in examples like these.
4. Decouples our custom content views and widgets from the templating features like toolbar.

3. Create User Interface

User interfaces are typically created in android using XML layouts as opposed by direct java coding.

This is an example fo declarative programming.

Advantages of Using XML over Java

No. Advantage
1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
2. It’s easily maintanable as the user interface is decoupled from your Java logic.
3. It’s easier to share or download code and safely test them before runtime.
4. You can use XML generated tools to generate XML

Here are our layouts for this project:

activity_main.xml

 

  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.

Here are some of the widgets, views and viewgroups that get employed”

No. View/ViewGroup Package Role
1. CordinatorLayout android.support.design.widget Super-powered framelayout that provides our application’s top level decoration and is also specifies interactions and behavioros of all it’s children.
2. AppBarLayout android.support.design.widget A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
3. ToolBar <android.support.v7.widget A ViewGroup that can provide actionbar features yet still be used within application layouts.
4. FloatingActionButton android.support.design.widget An circular imageview floating above the UI that we can use as buttons.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 
    
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_fitsSystemWindows="true"
    tools_context="com.tutorials.hp.dialogfragmentrecyclerview.MainActivity">

    <android.support.design.widget.AppBarLayout
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android_id="@+id/toolbar"
            android_layout_width="match_parent"
            android_layout_height="?attr/actionBarSize"
            android_background="?attr/colorPrimary"
            app_popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android_id="@+id/fab"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_gravity="bottom|end"
        android_layout_margin="@dimen/fab_margin"
        android_src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

content_main.xml

This layout gets included in your activity_main.xml.
You define your UI widgets right here.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_paddingBottom="@dimen/activity_vertical_margin"
    android_paddingLeft="@dimen/activity_horizontal_margin"
    android_paddingRight="@dimen/activity_horizontal_margin"
    android_paddingTop="@dimen/activity_vertical_margin"
    app_layout_behavior="@string/appbar_scrolling_view_behavior"
    tools_context="com.tutorials.hp.dialogfragmentrecyclerview.MainActivity"
    tools_showIn="@layout/activity_main">

    <TextView
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_text="Hello World!" />
</RelativeLayout>
fraglayout.xml

This layout will be inflated to our dialog fragment.

It will contain our RecyclerView as our adapterview:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android_orientation="vertical" android_layout_width="match_parent"
    android_layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android_id="@+id/mRecyerID"
        android_layout_width="match_parent"
        android_layout_height="wrap_content"></android.support.v7.widget.RecyclerView>

</LinearLayout>
model.xml

This will layout will be inflated into the View items for our RecyclerView.

Basically a CardView for each recyclerview item.

Contains a simple TextView:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 
    android_id="@+id/mCard"
    android_orientation="horizontal"
    android_layout_width="match_parent"
    
    android_layout_margin="10dp"
    card_view_cardCornerRadius="10dp"
    card_view_cardElevation="10dp"

    android_layout_height="wrap_content">

    <RelativeLayout
        android_layout_width="match_parent"
        android_layout_height="match_parent">

        <TextView
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_textAppearance="?android:attr/textAppearanceLarge"
            android_text="Name"
            android_id="@+id/nameTxt"
            android_padding="10dp"
            android_layout_alignParentLeft="true"
             />

    </RelativeLayout>
</android.support.v7.widget.CardView>

4. Create Java Classes

Android apps are written in Java programming language so lets create some classes.

1. MyHolder.java

Our ViewHolder class.

package com.tutorials.hp.dialogfragmentrecyclerview.mRecycler;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.tutorials.hp.dialogfragmentrecyclerview.R;

public class MyHolder extends RecyclerView.ViewHolder {

    TextView nameTxt;

    public MyHolder(View itemView) {
        super(itemView);
        nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);
    }
}
2. MyAdapter.java

Our recyclerview adapter class:

package com.tutorials.hp.dialogfragmentrecyclerview.mRecycler;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.tutorials.hp.dialogfragmentrecyclerview.R;

public class MyAdapter extends RecyclerView.Adapter<MyHolder> {

    Context c;
    String[] tvshows;

    public MyAdapter(Context c, String[] tvshows) {
        this.c = c;
        this.tvshows = tvshows;
    }

    //INITIALIE VH
    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,parent,false);
        MyHolder holder=new MyHolder(v);
        return holder;
    }

    //BIND DATA
    @Override
    public void onBindViewHolder(MyHolder holder, int position) {
       holder.nameTxt.setText(tvshows[position]);
    }

    @Override
    public int getItemCount() {
        return tvshows.length;
    }
}
TVShowFragment.java

This is our DialogFragment. It derives from android.app.DiloagFragment.

This class will show our RecyclerView:

package com.tutorials.hp.dialogfragmentrecyclerview;

import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.tutorials.hp.dialogfragmentrecyclerview.mRecycler.MyAdapter;

public class TVShowFragment extends DialogFragment {

    String[] tvshows={"Crisis","Blindspot","BlackList","Game of Thrones","Gotham","Banshee"};
    RecyclerView rv;
    MyAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView=inflater.inflate(R.layout.fraglayout,container);

        //RECYCER
        rv= (RecyclerView) rootView.findViewById(R.id.mRecyerID);
        rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));

        //ADAPTER
        adapter=new MyAdapter(this.getActivity(),tvshows);
        rv.setAdapter(adapter);

        this.getDialog().setTitle("TV Shows");

        return rootView;
    }
}

4. MainActivity.java

Our MainActivity.
It will contain a button that when clicked will show our DialogFragment:

package com.tutorials.hp.dialogfragmentrecyclerview;

import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

         final FragmentManager fm=getFragmentManager();
        final  TVShowFragment tv=new TVShowFragment();

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              tv.show(fm,"TV_tag");
            }
        });
    }

}

Example 2 – Android DialogFragment – ListView Search/Filter

 

The idea of dialogs is great because we can pop them out from nowhere. The user can then perform his thing then dismiss the dialog.

In this example we create a dialogfragment that gets displayed when a simple button is clicked from our main activity.

Our dialogfragment will contain a simple ListView and a SearchView. The ListView will contain a List of players.

The searchview can then be used to search the players from the list.

1. Our MainActivity Class

This is our main activity.

As a class it’s an activity since it derives from android.app.Activity.

No. Responsibility
1. It is our launcher and only activity.
2. It will contain a button which when clicked we show a dialogfragment.
3. It maintains a FragmentManager which helps in showing of our dialogfragment.
package com.tutorials.dialogfragmenter;

import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

  Button btn;

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

        final FragmentManager fm=getFragmentManager();
        final PlayersFragment p=new PlayersFragment();

        btn=(Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View arg0) {
        // TODO Auto-generated method stub
        p.show(fm, "Best Players");
      }
    });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

2. Our PlayerFragment class.

This is our PlayerFragment class.

No. Responsibility
1. Derives from android.app.DialogFragment hence making it a DialogFragment.
2. We’ll reference a ListView and SearchView here. ListView will be our adapterview while we’ll use a searchview for inputting our search terms.
3. We’ll dismiss our dialogfragment when the dismiss button is clicked.
package com.tutorials.dialogfragmenter;

import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

public class PlayersFragment extends DialogFragment {

  Button btn;
  ListView lv;
  SearchView sv;
  ArrayAdapter<String> adapter;
  String[] players={"Lionel Messi","Christiano Ronaldo","Neymar","Gareth Bale"};

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View rootView=inflater.inflate(R.layout.sports, null);

    //SET TITLE DIALOG TITLE
    getDialog().setTitle("Best Players In The World");

    //BUTTON,LISTVIEW,SEARCHVIEW INITIALIZATIONS
    lv=(ListView) rootView.findViewById(R.id.listView1);
    sv=(SearchView) rootView.findViewById(R.id.searchView1);
    btn=(Button) rootView.findViewById(R.id.dismiss);

    //CREATE AND SET ADAPTER TO LISTVIEW
    adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,players);
    lv.setAdapter(adapter);

    //SEARCH
    sv.setQueryHint("Search..");
    sv.setOnQueryTextListener(new OnQueryTextListener() {

      @Override
      public boolean onQueryTextSubmit(String txt) {
        // TODO Auto-generated method stub
        return false;
      }

      @Override
      public boolean onQueryTextChange(String txt) {
        // TODO Auto-generated method stub

        adapter.getFilter().filter(txt);
        return false;
      }
    });

    //BUTTON
    btn.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View arg0) {
        // TODO Auto-generated method stub
        dismiss();
      }
    });

    return rootView;
  }

}

3. Our MainActivity Layout

This is our main activity layout.

No. Responsibility
1. Contains a button that when clicked will open our dialogfragment.
<RelativeLayout 
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_paddingBottom="@dimen/activity_vertical_margin"
    android_paddingLeft="@dimen/activity_horizontal_margin"
    android_paddingRight="@dimen/activity_horizontal_margin"
    android_paddingTop="@dimen/activity_vertical_margin"
    tools_context=".MainActivity" >

    <Button
        android_id="@+id/button1"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_alignParentLeft="true"
        android_layout_alignParentTop="true"
        android_layout_marginLeft="97dp"
        android_layout_marginTop="163dp"
        android_text="Show" />

</RelativeLayout>

4. OUR PlayerFragment Layout

This is our dialog fragment’s layout.

Here are it’s roles:

No. Responsibility
1. Define a ListView which will display of list of items.
2. Define a SearchView for searching/filtering our data.
3. Define a button for dismissing our dialogfragment.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_orientation="vertical" >

    <SearchView
        android_id="@+id/searchView1"
        android_layout_width="match_parent"
        android_layout_height="wrap_content" >
    </SearchView>

    <ListView
        android_id="@+id/listView1"
        android_layout_width="match_parent"
        android_layout_height="326dp" >
    </ListView>

    <Button
        android_id="@+id/dismiss"
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_text="Dismiss" />

</LinearLayout>

Our Manifest

Our android manifest.xml. Our activity is registered here.

<?xml version="1.0" encoding="utf-8"?>
<manifest 
    package="com.tutorials.dialogfragmenter"
    android_versionCode="1"
    android_versionName="1.0" >

    <uses-sdk
        android_minSdkVersion="19"
        android_targetSdkVersion="19" />

    <application
        android_allowBackup="true"
        android_icon="@drawable/ic_launcher"
        android_label="@string/app_name"
        android_theme="@style/AppTheme" >
        <activity
            android_name="com.tutorials.dialogfragmenter.MainActivity"
            android_label="@string/app_name" >
            <intent-filter>
                <action android_name="android.intent.action.MAIN" />

                <category android_name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>