Saturday, October 6, 2018

Android Activity as a dialog popup box

Let say I have an Activity named PasswordCreatePage which has child dialogs as well. Now, I want to display this activity as a dialog for another activity. At this stage we need something special to do. First let see PasswordCreatePage class below:
package com.pritom.kumar;

import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.Window;

public class PasswordCreatePage extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // If you want to hide title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // Setting dialog box title
        setTitle(R.string.set_password);
        // Setting layout page at this stage
        setContentView(R.layout.password_create_page);
        // If you want to finish this activity on touch outside of this dialog
        this.setFinishOnTouchOutside(false);
        // Setting dialog box width 100% and height as content height
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }
}
Now we will create/modify a theme in PROJECT/RES/VALUES named STYLES.XML, add below content to the file (actually this file describes the style of the dialog box):
<style name="AlertDialogCustomWithTitle" parent="@android:style/Theme.Dialog">
    <item name="android:buttonStyle">@style/ButtonColor</item>
</style>
At this stage we will create a layout page with below content (it's actually a simple layout page):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:padding="10dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/password" />

</LinearLayout>
Now we will put an entry to ANDROIDMANIFEST.XML related to our Activity:
<activity
    android:name=".PasswordCreatePage"
    android:theme="@style/AlertDialogCustomWithTitle"
    android:excludeFromRecents="true">
</activity>
We are done. If you open this activity, this will open as a Dialog Popup Box.

No comments:

Post a Comment