23

I have a problem with popup window. I want to create popup window with my own layout. This is code:

public class PopupWindowView extends PopupWindow{

    PopupWindow popup;
    boolean click = true;
    LayoutParams params;
    RelativeLayout mainLayout;
    TextView tv;
    LinearLayout layout;
    ImageView chooseFlag;

    public void createPopupWindow(Activity act){
        popup = new PopupWindow(act);
        chooseFlag = (ImageView) act.findViewById(R.id.login_choose_flag);
        mainLayout = (RelativeLayout) act.findViewById(R.id.login_layout);
        tv = new TextView(act);
        layout = new LinearLayout(act);
        //layout = (LinearLayout) findViewById(R.id.popuplayout);
        chooseFlag.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (click) {
                    int[] values = new int[2]; 
                    v.getLocationOnScreen(values);
                    popup.showAtLocation(mainLayout, Gravity.NO_GRAVITY, 10, 10);
                    popup.update(values[0], values[1], 300, 80);
                    click = false;
                } else {
                    popup.dismiss();
                    click = true;
                }
            }
        });
        params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        layout.setOrientation(LinearLayout.VERTICAL);
        tv.setText("Hi this is a sample text for popup window");
        layout.addView(tv, params);
        popup.setContentView(layout);
    }
}

and this is layout which I want to set in my popup window:

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

    <LinearLayout
        android:id="@+id/popuplayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" 
        android:background="@color/patient_button_bg">
    </LinearLayout>

</LinearLayout>

In my class I can't use findbyid method because this is not Activity. How I can set my own layout in popup widow in my class?

Edit: this is stack trace where I get error:

03-01 09:48:48.761: E/AndroidRuntime(16776): FATAL EXCEPTION: main
03-01 09:48:48.761: E/AndroidRuntime(16776): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.ViewGroup.addViewInner(ViewGroup.java:3337)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.ViewGroup.addView(ViewGroup.java:3208)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.ViewGroup.addView(ViewGroup.java:3188)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.widget.PopupWindow.preparePopup(PopupWindow.java:969)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.widget.PopupWindow.showAtLocation(PopupWindow.java:840)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.widget.PopupWindow.showAtLocation(PopupWindow.java:813)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at pl.asseco.amms.mobile.tools.PopupWindowView$1.onClick(PopupWindowView.java:44)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.View.performClick(View.java:3558)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.View$PerformClick.run(View.java:14152)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.os.Handler.handleCallback(Handler.java:605)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.os.Handler.dispatchMessage(Handler.java:92)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.os.Looper.loop(Looper.java:137)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.app.ActivityThread.main(ActivityThread.java:4514)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at java.lang.reflect.Method.invokeNative(Native Method)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at java.lang.reflect.Method.invoke(Method.java:511)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at dalvik.system.NativeStart.main(Native Method)

Edit Activity which use popup:

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

    mainMenuGenerator = new MainMenuGenerator();
    mainMenuGenerator.generateMainMenu(this);
    mainMenuGenerator.hideIcons();
    popup = new PopupWindowView();

    popup.createPopupWindow(this);

}
Manoj Perumarath
  • 9,337
  • 8
  • 56
  • 77
user1302569
  • 7,131
  • 13
  • 46
  • 66

6 Answers6

29

try this code:

private void showSortPopup(final Activity context, Point p) 
{
       // Inflate the popup_layout.xml
       LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.llSortChangePopup);
       LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       View layout = layoutInflater.inflate(R.layout.sort_popup_layout, viewGroup);

       // Creating the PopupWindow
       changeSortPopUp = new PopupWindow(context);
       changeSortPopUp.setContentView(layout);
       changeSortPopUp.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
       changeSortPopUp.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
       changeSortPopUp.setFocusable(true);

       // Some offset to align the popup a bit to the left, and a bit down, relative to button's position.
       int OFFSET_X = -20;
       int OFFSET_Y = 95;

       // Clear the default translucent background
       changeSortPopUp.setBackgroundDrawable(new BitmapDrawable());

       // Displaying the popup at the specified location, + offsets.
       changeSortPopUp.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y + OFFSET_Y);


       // Getting a reference to Close button, and close the popup when clicked.
       Button close = (Button) layout.findViewById(R.id.close);
       close.setOnClickListener(new OnClickListener() {

         @Override
         public void onClick(View v) {
           changeSortPopUp.dismiss();
         }
       });

}
Volodymyr Kulyk
  • 6,455
  • 3
  • 36
  • 63
Emil Adz
  • 40,709
  • 36
  • 140
  • 187
  • 1
    useful, thanks ! `clear the default translucent background`, it was driving me up the wall (especially not finding what in my layout was causing it) – YvesLeBorg Apr 18 '17 at 15:51
8

You can use following code. you need to use PopupWindow for this.

PopupWindow mpopup;   

then you need to inflate your view.

    View popUpView = getLayoutInflater().inflate(R.layout.activity_login,
            null); // inflating popup layout
    mpopup = new PopupWindow(popUpView, LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT, true); // Creation of popup
    mpopup.setAnimationStyle(android.R.style.Animation_Dialog);
    mpopup.showAtLocation(popUpView, Gravity.CENTER, 0, 0); // Displaying popup  

if your layout have some item then you need bind that item with your view.

    TextView some = (TextView) popUpView.findViewById(R.id.some);       
    Button btnCancel = (Button) popUpView.findViewById(R.id.btnCancel);  

onClickListener of your popup windows item.

    btnCancel.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mpopup.dismiss();
        }
    });   

You can dismiss your PopupWindow using mpopup.dismiss();

Sandip Armal Patil
  • 6,241
  • 21
  • 93
  • 160
4

You can use LayoutInflater

LayoutInflater inflater = (LayoutInflater) act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_layout, null); //custom_layout is your xml file which contains popuplayout
LinearLayout layout = (LinearLayout) view.findViewById(R.id.popuplayout);
Waqas
  • 6,812
  • 2
  • 33
  • 50
  • I used your solution but I get error:java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. – user1302569 Mar 01 '13 at 08:50
  • As per exception it seems that you are trying to add a view which already has been added previously to a different layout, could you please at which line are you getting this exception? – Waqas Mar 01 '13 at 09:41
  • can't you debug and see at which specific line it thorws this error? From stack trace, you get this error inside preparePopup method – Waqas Mar 01 '13 at 10:13
  • Ok, when I run application debugger run and everything is ok. But When I click on this button I get error and debugger stop. It looks like method create first time in onCreate in Activity and when you click on button to I get error. I pasted onCreate from activity – user1302569 Mar 01 '13 at 10:26
  • You mean it works when it is being called from onCreate but later on button click it wont? Where is source of your button click event? – Waqas Mar 01 '13 at 10:29
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/25349/discussion-between-user1302569-and-waqas) – user1302569 Mar 01 '13 at 10:30
  • yes, When is creating is everything ok, but when I clock on button I get error. This button is in popup class. Choosenflag – user1302569 Mar 01 '13 at 10:31
3

try this......

public void popUpWindow() {
    final Dialog dialog = new Dialog(MainActivity.this);
    dialog.setContentView(R.layout.client_details);
    dialog.setTitle("Client Details");
    dialog.show();
}
Thamays
  • 2,978
  • 26
  • 31
1

Hi check this post consists of Solution to your question

Try this code :

public class ShowPopUp extends Activity {

PopupWindow popUp;
LinearLayout layout;
TextView tv;
LayoutParams params;
LinearLayout mainLayout;
Button but;
boolean click = true;


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    popUp = new PopupWindow(this);
    layout = new LinearLayout(this);
    mainLayout = new LinearLayout(this);
    tv = new TextView(this);
    but = new Button(this);
    but.setText("Click Me");
    but.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            if (click) {
                popUp.showAtLocation(mainLayout, Gravity.BOTTOM, 10, 10);
                popUp.update(50, 50, 300, 80);
                click = false;
            } else {
                popUp.dismiss();
                click = true;
            }
        }

    });
    params = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    layout.setOrientation(LinearLayout.VERTICAL);
    tv.setText("Hi this is a sample text for popup window");
    layout.addView(tv, params);
    popUp.setContentView(layout);
    // popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
     mainLayout.addView(but, params);
     setContentView(mainLayout);
   }
 }
Community
  • 1
  • 1
androidgeek
  • 3,440
  • 1
  • 15
  • 27
0
    alert=(Button)findViewById(R.id.click);
    detail=(ImageView)findViewById(R.id.goDetail);

    alert.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // custom dialog

            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.custom);
            dialog.setTitle(Html.fromHtml("<font color='#EC407A'>About</font>"));
            Button dialogButton = (Button) dialog.findViewById(R.id.dialogOK);
            ImageView img = (ImageView) dialog.findViewById(R.id.goDetail);
            // if button is clicked, close the custom dialog
            dialogButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    Toast.makeText(getApplicationContext(),"Dismissed..!!",Toast.LENGTH_SHORT).show();
                }
            });
            img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    i=new Intent(getApplication(),CustomDetail.class);
                    setIntent(i);
                    Toast.makeText(Dashboard.this, "Check detail ", Toast.LENGTH_SHORT).show();
                }
            });
            dialog.show();
        }
ADyson
  • 57,178
  • 14
  • 51
  • 63
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – J. Chomel Mar 31 '17 at 08:32