Monday, July 23, 2012

How to create popup window in android

Hello Friends,
Today I am going to explore a simple Demo for Popup window in android ,which gives you
an idea , how to create a popup window with some text and close button.

1)Print Screen
i)

ii)


2)manisfest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.popup.window"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="7" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".PopUpWinndowDemoActivity"
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>


3)PopUpWinndowDemoActivity.java file
package com.popup.window;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupWindow;

public class PopUpWinndowDemoActivity extends Activity {
Button btnClosePopup;
Button btnCreatePopup;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnCreatePopup = (Button) findViewById(R.id.button1);
btnCreatePopup.setOnClickListener(new OnClickListener() {

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

}

private PopupWindow pwindo;

private void initiatePopupWindow() {
try {
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) PopUpWinndowDemoActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.screen_popup,
(ViewGroup) findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 300, 370, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);

btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
btnClosePopup.setOnClickListener(cancel_button_click_listener);

} catch (Exception e) {
e.printStackTrace();
}
}

private OnClickListener cancel_button_click_listener = new OnClickListener() {
public void onClick(View v) {
pwindo.dismiss();

}
};

}

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

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />

</LinearLayout>



5)screen_popup.xml file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/popup_element"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#444444"
android:orientation="vertical"
android:padding="10sp" >

<TextView
android:id="@+id/txtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5sp"
android:text="Hello!" />

<Button
android:id="@+id/btn_close_popup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Close" />

54 comments :

  1. Great little tutorial! How do you dismiss the popup window with a tab on the side of the window instead of using a cancel button?

    ReplyDelete
  2. Hi Tim just add one line of code-
    pwindo.setBackgroundDrawable(new BitmapDrawable());

    It will cancel your popup on tab any where in window..

    LayoutInflater inflater = (LayoutInflater) PopUpWinndowDemoActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.screen_popup,(ViewGroup) findViewById(R.id.popup_element));
    pwindo = new PopupWindow(layout, 100, 170, true);
    pwindo.setBackgroundDrawable(new BitmapDrawable());
    pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
    btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
    btnClosePopup.setOnClickListener(cancel_button_click_listener);

    ReplyDelete
  3. Thank you! Works perfectly, just how I wanted it to be :D

    ReplyDelete
  4. say for instance you were trying to have the pop up show up on the 3rd start of the app.. and it had 2 buttons on the buttom of the pop up - remind me later, and rate this app. How would you implement that?

    ReplyDelete
    Replies
    1. Hi Steve!
      Please try my below post hope it will help you.
      1)http://www.androidhub4you.com/2012/09/menu-dialog-demo-in-android.html

      2)http://www.androidhub4you.com/2012/09/alert-dialog-box-or-confirmation-box-in.html

      Thanks,

      Delete
  5. Please send this Demo miralparsaniya4@gmail.com

    ReplyDelete
    Replies
    1. Miral, You are regular reader on my blog.
      Thank you so much for that..
      Miral this is a very simple code so please copy paste it from above.
      If you have difficulty please let me know..

      Thanks,

      Delete
  6. Hi, I wonder, is there any way to make full screen or scalable pop up, like px and dp in text? I try to make pop up menu that used to input data to SQLite, so I want the pop up size is not have much difference across platform. Thanks

    ReplyDelete
    Replies
    1. I am not sure but please but i think instead of below line-
      pwindo = new PopupWindow(layout, 300, 370, true);

      you should use some thing like that-
      pwindo = new PopupWindow(layout, matchParrent, matchParrent, true)

      if there is no way to do it then try to get device height, width and put instead of fix values..

      :)

      Delete
  7. dude ...where to write this code ...and how to execute this please kindly replay

    ReplyDelete
    Replies
    1. You can create a demo project and putt all code inside that or you can use it in your project also....

      Delete
  8. This comment has been removed by the author.

    ReplyDelete
  9. How can i make and editText invisible in the pop up.
    I tried this but it doesn't work..
    ((EditText)pwindo.getContentView().findViewById(R.id.editTextpass31)).setVisibility(View.GONE);

    ReplyDelete
    Replies
    1. Hi just add an edittext in your layout-
      EditText
      android:id="@+id/editText1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:ems="10"

      And in your activity-
      private void initiatePopupWindow() {
      try {
      // We need to get the instance of the LayoutInflater
      LayoutInflater inflater = (LayoutInflater) PopUpWinndowDemoActivity.this
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      View layout = inflater.inflate(R.layout.screen_popup,
      (ViewGroup) findViewById(R.id.popup_element));
      pwindo = new PopupWindow(layout, 300, 370, true);
      pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);

      btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
      editBox=(EditText)layout.findViewById(R.id.editText1);
      editBox.setVisibility(View.INVISIBLE);
      btnClosePopup.setOnClickListener(cancel_button_click_listener);

      } catch (Exception e) {
      e.printStackTrace();
      }
      }

      Thanks,

      Delete
  10. i need a popup in which listview is attached in that..can you help me manish

    ReplyDelete
    Replies
    1. Yes sure dear!
      There are two way to do this task-
      1)Create dynamic listview inside popup window and perform action what you want.like-
      AlertDialog.Builder alert = new AlertDialog.Builder(this);

      alert.setTitle("Add Description!");
      alert.setMessage("Please add description in below box..");

      // Set an EditText view to get user input
      final ListView list = new ListView(this);
      alert.setView(list);

      2)You can Create ListView inside any layout and call this using inflate..

      Thanks!

      Delete
  11. Hi Manish,

    Can we add a popup window at a specific LatLng point?
    As pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0); will display it on center. As I need to add muliple buttons on infowindow, the require infowindow contains 4 buttons but while implementing in infowindow only one click event works, as the infowindow appears on click of other infowindow, so getting many problems while implementing. So i plan to add popwindow as infowindow on map if possible.

    ReplyDelete
    Replies
    1. Hi Swati,

      I think you should use Marker option and Google map version-2. On tab any marker you can perform any action like-
      1)Add Marker-
      private void drawMarker(LatLng point){
      // Creating an instance of MarkerOptions
      MarkerOptions markerOptions = new MarkerOptions();

      // Setting latitude and longitude for the marker
      markerOptions.position(point);

      // Adding InfoWindow title
      markerOptions.title("Location Coordinates");

      // Adding InfoWindow contents
      markerOptions.snippet(Double.toString(point.latitude) + "," + Double.toString(point.longitude));

      // Adding marker on the Google Map
      googleMap.addMarker(markerOptions);

      }

      2-Press on Marker-
      @Override
      public boolean onMarkerClick(Marker marker) {
      // TODO Auto-generated method stub
      //System.out.println("Marker lat long=" + marker.getPosition());
      popupWindow();

      return false;
      }

      I think it should work for you...

      Delete
  12. Hi Manish am sakthidasan
    .. i done one project .. but i do want add some specification
    such as.. pop up menu creation (that is when i click button want to show the menu in that layout and that menu want to come from right to left eg:picart app). as vertical
    please give a solution me

    ReplyDelete
    Replies
    1. Use Inflate layout with animation. left to right or how you want its up to you.
      means use inflator instead of menu, it will be same what you want..

      Thanks!

      Delete
  13. how to create layout support multiple screen or all devices

    ReplyDelete
    Replies
    1. 1)Use Relative-layout how much possible.
      2)Don't fix height, width hard coded, always use wrap and match parent.
      3)Use 4 images for all drawable i.e.- drawable-ldpi,drawable-mdpi,drawable-hdpi,drawable-xhdpi.
      4)And if any page needed create 4 layout for that also like-layout-mdpi,layout-xhdpi etc...

      Hope it will help you..
      Thanks!

      Delete
  14. I have a gridview wit a few images.once i click the image i want the background to be a little blurry so that the image can popup.can u help me with this?

    ReplyDelete
  15. Hi When i implement your code in 4.1.2 the onclick listener doesn't seem to fire and dismiss the window is this just due to the version or am i doing something wrong here?

    ReplyDelete
    Replies
    1. Never mind i fixed it by putting layout.findViewById when instantiating the button

      Delete
    2. hehehehhe :)
      Great I like it you, because after solve your problem you reply back. it will help to other guys.

      Thanks!

      Delete
  16. This comment has been removed by the author.

    ReplyDelete
  17. I was looking into your blog and i'm the beginner in android! In view group u said R.id.popup_element, what is that actually??

    ReplyDelete
  18. HI!
    Actually I am using LayoutInflater inflater here, it is used when you want add any other view inside your activity.
    (ViewGroup) findViewById(R.id.popup_element));

    so popup_element is the id of LinearLayout, screen_popup.xml.

    Thanks!

    ReplyDelete
  19. Very nice tutorial, short and fast, thanks!!

    ReplyDelete
  20. Hi Manish :)

    can we make pop out appears on the next page after clicking the button?

    ReplyDelete
    Replies
    1. yes sure just create that popup on next page inside onCreate method().

      Delete
  21. hi Manish,

    when i m clicking the close button nothing i happening so plz tell wht to write so dat it can came to original shape

    ReplyDelete
    Replies
    1. It should work. Did you make any change in code? please see this line-
      pwindo.dismiss();

      above line is used here for close popup window..

      Delete
    2. the same code as it is i had used but when i clicked on close button its not working

      Delete
    3. I don't believe it. no one complain it yet. and me to using same code in many application. can you tell me which device you are using for testing? Have you tried it any other device?

      Delete
  22. Hi Manish,
    I hav to create a Popup using a background service.how can i do it.??
    Plz help me out.

    Thank you

    ReplyDelete
    Replies
    1. background service means? web-services or background thread or using android Services? I think you are talking about android Services.In side you service class -
      @Override
      public void onStart(Intent intent, int startId) {
      //here create a receiver which will call a intent for your popup.

      Thanks!

      Delete
  23. hey when i take edit text in popup window then edit text is not taking input from user....how to solve this problem

    ReplyDelete
    Replies
    1. I have created many time and its working fine for me that's mean you are doing some thing wrong. Please share your code so i can find out reason.

      Thanks,

      Delete
    2. Just call this login method from anywhere-

      public void login() {
      // ================Forget password popup open
      AlertDialog.Builder alert = new AlertDialog.Builder(this);

      alert.setTitle("Login here!");
      alert.setMessage("*use numeric key only!");

      // Set an EditText view to get user input
      final EditText input = new EditText(this);
      input.setHint("passcode!");
      input.setInputType(InputType.TYPE_CLASS_NUMBER);
      input.setTransformationMethod(PasswordTransformationMethod.getInstance());
      alert.setView(input);

      alert.setNegativeButton("Cancel",
      new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
      // Canceled.
      finish();
      }
      });

      alert.setPositiveButton("Done", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
      String textLogin=input.getText().toString();
      if (textLogin.equals("") || textLogin.equals(null)) {
      Toast.makeText(SplashActivity.this,
      "empty field not allow!", Toast.LENGTH_SHORT)
      .show();
      }
      }

      });

      alert.show();
      }

      Delete
  24. Hey manish,

    Your tutorial really helped me out. I was just wondering, how would I set up a second button in that same activity which opens a new pop up window? Let's say that activity has multiple buttons and each button opens their own pop up window. I am really struggling here please help me out

    ReplyDelete
    Replies
    1. Have you tried? Is there any problem?
      I think just create multiple popup like-
      private PopupWindow pwindo1;
      private PopupWindow pwindo2;
      private PopupWindow pwindo3;

      and open different one for all buttons.

      Delete
    2. Hi,

      I have done that indeed, only i changed private to public (to be honest i still don't know what the difference is). But i can open more pop up windows after i created pwindo1,2,3 etc. The only problem i am facing now is that the close button only works for the first pop up window and not for the second, third or etc.. But i can close them when i touch anywhere outside the box.

      Maybe you know why that occurs?

      And really appreciate that you answered me. :)

      Delete
  25. Hey I just want a pop up dialog as a sms is received or i may trigger it with a timer.
    eg. if u have applock installed in ur phone and wen u instal a new app in ur phone then a dialog appears saying if u want to lock the app or not.
    will u plz help me wid the code.
    thank you

    ReplyDelete
  26. Hi dear, I want to show pop on activity start.(i.e without button click). How i can do so?
    Kindly reply as soon as possible.

    ReplyDelete
  27. Nice one bro! thank you very much for sharing knowledge.

    ReplyDelete