Android DialogFragment


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.

Android DialogFragment Example

Let's see a Kotlin android Dialog Fragment example with Kotlin.

Kotlin Android DialogFragment with ListView

Tools

  1. IDE: Android Studio - android's offical android IDE supported by Jetbrains and Google.
  2. Language : Kotlin -Statically Typed Language first developed by Jetbrains.
  3. Emulator : Nox Player - An emulator fast enough for my slow machine.

Gradle Scripts

We start by exploring our gradle scripts.

(a). build.gradle(App)

Here's our app level build.gradle file. We have the dependencies DSL where we add our dependencies.

This file is called app level build.gradle since it's located in the app folder of the project.

If you are using Android Studio version 3 and above use implementation keyword while if you are using a version less than 3 then still use the compile keyword.

Once you've modified this build.gradle file you have to sync your project. Android Studio will indeed prompt you to do so.

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "info.camposha.kotlindialogfragment"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0-rc01'
}

You can also see that we have started by applying two kotlin-specific plugins in our build.gradle file:

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

that is kotlin-android and kotlin-android-extensions.

Kotlin Code

Android apps can be mainly written in Java or Kotlin. These days however there are many frameworks like Flutter also which use languages like Dart.

In this class we are using Kotlin programming language.

We will have these classes in our project.

(a). PioneersFragment.kt

Represents our FragmentDialog and will infact derive from it.

1. Creating a DialogFragment

We start by creating a Kotlin class that derives from android.support.v4.app.DialogFragment. We use the support library fragment since android.app.DialogFragment is deprecated.

class PioneersFragment : DialogFragment() {..}

Note that the above statement has included a default empty constructor for our DialogFragment. We do this using the brackets(()) in Kotlin.

2. Overriding DialogFragment's OnCreateView()

We will then override the onCreateView() method of the Fragment class.

 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {..}

We've passed three parameters:

  1. LayoutInflater object.
  2. ViewGroup object.
  3. Bundle object.

3. Inflating a Layout into a DialogFragment

Inside the method first we inflate the R.layout.fraglayout layout via the inflate method, using the LayoutInflater instance.

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

4. Creating a Kotlin Array

Then create a Kotlin array using the arrayOf() method. This will act as our data source to host pioneers. This is what we will bind to the ListView which we will show in our DialogFragment.

var pioneers = arrayOf("Dennis Ritchie", "Rodney Brooks", "Sergey Brin", "Larry Page", "Cynthia Breazeal", "Jeffrey Bezos", "Berners-Lee Tim", "Centaurus A", "Virgo Stellar Stream")

5. Binding a ListView to Kotlin Array using ArrayAdapter

We then reference our ListView and set it's adapter. We will use arrayadapter.

        val myListView = rootView.findViewById(R.id.myListView) as ListView
        myListView!!.adapter = ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, pioneers)

6. Setting a DialogFragment Title

We set the DialogFragment's title using the setTitle() method, you pass a String to this method.

        this.dialog.setTitle("Tech Pioneers")

7. Listening to ListView's Click events in Kotlin

Let's say we want to show a Toast message when a ListView is clicked, showing the clicked item:

        myListView.setOnItemClickListener {
            adapterView,
            view,
            position,
            l
            -> Toast.makeText(activity, pioneers[position], Toast.LENGTH_SHORT).show()
        }

Here's the full code of PioneersFragment class:

package info.camposha.kotlindialogfragment

import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast

class PioneersFragment : DialogFragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val rootView = inflater.inflate(R.layout.fraglayout, container)
        var pioneers = arrayOf("Dennis Ritchie", "Rodney Brooks", "Sergey Brin", "Larry Page", "Cynthia Breazeal", "Jeffrey Bezos", "Berners-Lee Tim", "Centaurus A", "Virgo Stellar Stream")

        val myListView = rootView.findViewById(R.id.myListView) as ListView
        //with arrayadapter you have to pass a textview as a resource, and that is simple_list_item_1
        myListView!!.adapter = ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, pioneers)

        this.dialog.setTitle("Tech Pioneers")

        myListView.setOnItemClickListener {
            adapterView,
            view,
            position,
            l
            -> Toast.makeText(activity, pioneers[position], Toast.LENGTH_SHORT).show()
        }

        return rootView
    }
}
(c). MainActivity.kt

This is our MainActivity. It will contain a button that when clicked will show or open our DialogFragment.

1. Create an Activity in Kotlin

You just create a class, give it an identifier then make it derive from android.support.v7.app.AppCompatActivity:

class MainActivity : AppCompatActivity() {..}

2. Override the Activity's onCreate() method

The onCreate() is a method that gets raised when our activity's being created.

Here we call the onCreate() method of the super class. Then we use the setContentView() method to inflate our activity_main.xml:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

3. Referencing Widgets in Kotlin

You can reference widgets from their respective layout using the findViewById() method of the activity.

Like we do with our button.

        val openFragmentBtn = findViewById(R.id.openFragmentID) as Button

4. Obtain an Activity's FragmentManager

Fragments get hosted by Activities. Hence an activity maintains a supportFragmentManager as a property.

We can obtain it this way:

        val fm = supportFragmentManager

5. Open/Show a Fragment

We can open a Fragment or show it. But first we have to instantiate that Fragment:

        val pioneersFragment = PioneersFragment()

Then we can open it when the user clicks a button by invoking the show() method of the Fragment class:


        openFragmentBtn.setOnClickListener(object : View.OnClickListener {
            override fun onClick(view: View) {
                pioneersFragment.show(fm, "PioneersFragment_tag")
            }
        })

Here's the full code of the MainActivity:

package info.camposha.kotlindialogfragment

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val openFragmentBtn = findViewById(R.id.openFragmentID) as Button

        val fm = supportFragmentManager
        val pioneersFragment = PioneersFragment()

        openFragmentBtn.setOnClickListener(object : View.OnClickListener {
            override fun onClick(view: View) {
                pioneersFragment.show(fm, "PioneersFragment_tag")
            }
        })
    }
}
//end

Layout Resources

(a). activity_main.xml

This is our main activity's layout. It will contain our Button which when clicked will open our DialogFragment.

This layout will get inflated into the main activity's user interface. This will happen via the Activity's setContentView() method which will require us to pass it the layout.

We will do so inside the onCreate() method of Activity.

We use the following elements:

  1. RelativeLayout
  2. Button
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/openFragmentID"
        android:text="Open Fragment"
        android:background="@color/colorAccent"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
(b). fraglayout.xml

Our DialogFragment layout. This layout be inflated into the user interface for our Dialog Fragment.

It will contain a simple ListView.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/myListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Value Resources

(a). colors.xml

Our material design colors:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="material_amber_700">#ffffa000</color>
    <color name="material_amber_800">#ffff8f00</color>
    <color name="material_amber_900">#ffff6f00</color>
    <color name="material_amber_A100">#ffffe57f</color>
    <color name="material_amber_A200">#ffffd740</color>
    <color name="material_amber_A400">#ffffc400</color>

</resources>
(b). styles.xml

Our application's style.

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/material_amber_A400</item>
        <item name="colorPrimaryDark">@color/material_amber_900</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post