Posted By Our Mentors
Amreen Khan
Android Developer
animesh bansal
iphone App Developer
Devendra chouksey
Android Developer
Dilip Saket
IOS apps developer
Hemraj Jhariya
iOS Developer
Jaihind singh Rajput
Smart Phone App Dev
Mujahid khan
Android developer
Narendra Yadav
android developer
Narinder Gupta
Mobile App Architect
Pradeep singh Thakur
Mobile App Architect
Sanjay Sharma
Andriod Developer
Shakti Rajpal
IT Architect
Soniya Vishwakarma
iPhone App Developer
Sunil Raghuwanshi
iPhone App Developer
Supriya Kapse
Senior developer
View current Topics
How to Create Pop up in android? Android
Hi friends to day we learn how can we create a pop up in android . First of all question is what is pop up ? so here is the answer a popup window that can be used to display an arbitrary view. The popup windows is a floating container that appears on top of the current activity.
Posted By: Sanjay Sharma Date: 16 Jul 2012 View: 1515
      Rate This !!


Step 1. Create a project:

Project Name : VincentPopup

Package Name : vit.popup

Activity Name: QuickActionActivity.java

Step 2. Create main layout file for our activity class:

                      main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  android:id="@+id/quick_parent"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent">

 

       <TextView

              android:layout_width="fill_parent"

       android:layout_height="wrap_content"   

       android:gravity="center"

       android:textSize="17dp"

       android:textStyle="bold"

       android:text="New Quickaction Demo"/>

      

       <Button

              android:id="@+id/btn1"

              android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:layout_marginTop="10dp"

       android:text="Example 1"/>  

</LinearLayout>

 

Step 2. Create layout xml file  which is open as a  pop up:

                                 quickaction.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content" >

 

    <ImageView

        android:id="@+id/arrow_up"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:src="@drawable/quickaction_arrow_up" />

 

    <TextView

        android:id="@+id/quickaction_text"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_below="@+id/arrow_up"

        android:background="@drawable/quick_bg"

        android:fadingEdgeLength="0dip"

        android:gravity="center_horizontal"

        android:paddingLeft="20dip"

        android:paddingRight="15dip"

        android:paddingTop="5dip"

        android:text="Hi This Pop up created by Vincent It ."

        android:textColor="#ffffff"

        android:textSize="18dip"

        android:textStyle="bold" >

    </TextView>

 

    <ImageView

        android:id="@+id/arrow_down"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/quickaction_text"

        android:layout_marginTop="-1dip"

        android:src="@drawable/quickaction_arrow_down" />

 

</RelativeLayout>

 

Step 3. Now create a java class for creating pop up :-

OverView  : this class create a pop up which we used in other classes. In this class we define the functionality of pop up window .

                              PopupWindos.java

package net.londatiga.android;

 

import android.graphics.drawable.BitmapDrawable;

import android.graphics.drawable.Drawable;

 

import android.view.LayoutInflater;

import android.view.MotionEvent;

import android.view.View;

import android.view.WindowManager;

import android.view.View.OnTouchListener;

 

import android.widget.PopupWindow;

import android.content.Context;

 

public class PopupWindows {

       protected Context mContext;

       protected PopupWindow mWindow;

       protected View mRootView;

       protected Drawable mBackground = null;

       protected WindowManager mWindowManager;

      

       /**

        * Constructor.

        *

        * @param context Context

        */

       public PopupWindows(Context context) {

              mContext      = context;

              mWindow       = new PopupWindow(context);

 

              mWindow.setTouchInterceptor(new OnTouchListener() {

                    

                     public boolean onTouch(View v, MotionEvent event) {

                           if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {

                                  mWindow.dismiss();

                                 

                                  return true;

                           }

                          

                           return false;

                     }

              });

 

              mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

       }

      

       /**

        * On dismiss

        */ 

       protected void onDismiss() {            

       }

      

       /**

        * On show

        */

       protected void onShow() {        

       }

 

       /**

        * On pre show

        */

       protected void preShow() {

              if (mRootView == null)

                     throw new IllegalStateException("setContentView was not called with a view to display.");

      

              onShow();

 

              if (mBackground == null)

                     mWindow.setBackgroundDrawable(new BitmapDrawable());

              else

                     mWindow.setBackgroundDrawable(mBackground);

 

              mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);

              mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);

              mWindow.setTouchable(false);

              //mWindow.setFocusable(true);

              mWindow.setOutsideTouchable(true);

 

              mWindow.setContentView(mRootView);

       }

 

       /**

        * Set background drawable.

        *

        * @param background Background drawable

        */

       public void setBackgroundDrawable(Drawable background) {

              mBackground = background;

       }

 

       /**

        * Set content view.

        *

        * @param root Root view

        */

       public void setContentView(View root) {

              mRootView = root;

             

              mWindow.setContentView(root);

       }

 

       /**

        * Set content view.

        *

        * @param layoutResID Resource id

        */

       public void setContentView(int layoutResID) {

              LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

             

              setContentView(inflator.inflate(layoutResID, null));

       }

 

       /**

        * Set listener on window dismissed.

        *

        * @param listener

        */

       public void setOnDismissListener(PopupWindow.OnDismissListener listener) {

              mWindow.setOnDismissListener(listener); 

       }

 

       /**

        * Dismiss the popup window.

        */

       public void dismiss() {

              mWindow.dismiss();

       }

}

Step 3. Now create an other java class for creating pop up layout  :-

OverView  : This class extend PopupWindows and set layout of pop up in constructor of QuickAction.java and its position on screen by the use of show(View anchor) method in this method  anchor is a view on which we display our pop up . In this we also create a setText method which is show our message on screen.

                              QuickAction.java

package net.londatiga.android;

 

import android.content.Context;

import android.graphics.Rect;

import android.view.Gravity;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.view.ViewGroup.LayoutParams;

import android.widget.ImageView;

import android.widget.PopupWindow.OnDismissListener;

import android.widget.TextView;

 

/**

 * QuickAction dialog.

 *

 * @author sanjay sharma

 *

 */

public class QuickAction extends PopupWindows implements OnDismissListener {

       private ImageView mArrowUp;

       private ImageView mArrowDown;

 

       private LayoutInflater inflater;

       TextView quickaction_text;

      

       private OnDismissListener mDismissListener;

      

      

      

       private boolean mDidAction;

      

      

       private int mChildPos;   

  

      

       /**

        * Constructor.

        *

        * @param context Context

        */

       public QuickAction(Context context) {

              super(context);

             

              inflater      = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

 

      

              setRootViewId(R.layout.quickaction);

             

              mChildPos            = 0;

       }

      

       /**

     * Get action item at an index

     *

     * @param index  Index of item (position from callback)

     *

     * @return  Action Item at the position

     */

 

   

       /**

        * Set root view.

        *

        * @param id Layout resource id

        */

       public void setRootViewId(int id) {

              mRootView     = (ViewGroup) inflater.inflate(id, null);

 

              mArrowDown    = (ImageView) mRootView.findViewById(R.id.arrow_down);

              mArrowUp      = (ImageView) mRootView.findViewById(R.id.arrow_up);

              quickaction_text = (TextView)mRootView.findViewById(R.id.quickaction_text);

 

              //This was previously defined on show() method, moved here to prevent force close that occured

              //when tapping fastly on a view to show quickaction dialog.

              mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

             

              setContentView(mRootView);

       }

 

 

      

       /**

        * Show popup mWindow

        */

       public void show (View anchor) {

              preShow();

 

              int[] location             = new int[2];

             

              mDidAction                 = false;

             

              anchor.getLocationOnScreen(location);

 

              Rect anchorRect      = new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1]

                                   + anchor.getHeight());

 

              mRootView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

             

              int rootWidth              = mRootView.getMeasuredWidth();

              int rootHeight             = mRootView.getMeasuredHeight();

 

              int screenWidth      = mWindowManager.getDefaultDisplay().getWidth();

              //int screenHeight   = mWindowManager.getDefaultDisplay().getHeight();

 

              int xPos                   = (screenWidth - rootWidth) / 2;

              int yPos                   = anchorRect.top - rootHeight;

 

              boolean onTop        = true;

             

              // display on bottom

              if (rootHeight > anchor.getTop()) {

                     yPos   = anchorRect.bottom;

                     onTop  = false;

              }

 

              showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up), anchorRect.centerX());

             

             

      

              mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos);

             

       }

 

      

       /**

        * Show arrow

        *

        * @param whichArrow arrow type resource id

        * @param requestedX distance from left screen

        */

       private void showArrow(int whichArrow, int requestedX) {

        final View showArrow = (whichArrow == R.id.arrow_up) ? mArrowUp : mArrowDown;

        final View hideArrow = (whichArrow == R.id.arrow_up) ? mArrowDown : mArrowUp;

 

        final int arrowWidth = mArrowUp.getMeasuredWidth();

 

        showArrow.setVisibility(View.VISIBLE);

       

        ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams)showArrow.getLayoutParams();

       

        param.leftMargin = requestedX - arrowWidth / 2;

     

        hideArrow.setVisibility(View.INVISIBLE);

    }

      

       /**

        * Set listener for window dismissed. This listener will only be fired if the quicakction dialog is dismissed

        * by clicking outside the dialog or clicking on dialog item.

        */

       public void setOnDismissListener(QuickAction.OnDismissListener listener) {

              setOnDismissListener(this);

             

              mDismissListener = listener;

       }

      

       @Override

       public void onDismiss() {

              if (!mDidAction && mDismissListener != null) {

                     mDismissListener.onDismiss();

              }

       }

      

       /**

        * Listener for window dismiss

        *

        */

       public interface OnDismissListener {

              public abstract void onDismiss();

       }

      

       public void setText(String text)

       {

              quickaction_text.setText(text);

       }

}

Step 3. Now create an other java class for showing pop up this is our activity class :-

OverView  : This class is our activity class by the use of this class we display our pop up window . In this activity firstly we map our control then call show(view) method of QuickAction class. View is a view corresponding to this view we display our pop up. In mQuickAction.setOnDismissListener method we dismiss pop up with showing a toast.

                              QuickActionActivity.java

 

package net.londatiga.android;

 

import android.os.Bundle;

import android.os.Handler;

import android.content.Intent;

import android.app.Activity;

import android.widget.Button;

import android.widget.LinearLayout;

import android.widget.Toast;

 

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnTouchListener;

import android.view.Window;

 

public class QuickActionActivity extends Activity {

   QuickAction mQuickAction;

            Button example1Btn;

            LinearLayout quick_parent;

            @Override

            protected void onCreate(Bundle savedInstanceState) {

                        super.onCreate(savedInstanceState);

                       

                        setContentView(R.layout.main);

                       

                        quick_parent = (LinearLayout)findViewById(R.id.quick_parent);

                       

                       

                         example1Btn = (Button) findViewById(R.id.btn1);

                       

                         mQuickAction          = new QuickAction(this);

                         

                         quick_parent.setOnTouchListener(new OnTouchListener() {

                                               

                                                public boolean onTouch(View v, MotionEvent event) {

                                                            // TODO Auto-generated method stub

                                                           

                                                           

                                                            return true;

                                                }

                                    });

                       

                        mQuickAction.setOnDismissListener(new QuickAction.OnDismissListener() {

                                   

                                    public void onDismiss() {

                                                mQuickAction.mWindow.dismiss();

                                                Toast.makeText(getApplicationContext(), "Ups..dismissed", Toast.LENGTH_SHORT).show();

                                    }

                        });

                       

                       

                       

                        example1Btn.setOnClickListener(new View.OnClickListener() {                                   

                       

                                    public void onClick(View v) {

                                                //mQuickAction.setText("Hi Google");

                                                mQuickAction.show(v);

                                               

                                    }

                        });

                       

                       

            }

}

Step 4: When you run application you will get following screen as a output:

On clicking example1 button  you will get following  pop up as output:

That’s it

Full source code can be downloaded from the provided link

 

Any queries and suggestions are welcome

 

Regards,

Sanjay Sharma

Vicent IT Inc

I cheated on my boyfriend read open

Posted Queries