在Android中,如何在单击另一个自定义弹出窗口中的按钮时调用弹出窗口

时间:2015-05-05 16:17:51

标签: android popupwindow

点击主屏幕上的按钮后,我打开了一个对话框。 单击对话框中的按钮,将打开一个弹出屏幕。以下是代码。这部分工作正常。

final Dialog dialog = new Dialog(this,R.style.FullHeightDialog);

// dialog box layout is layout.xml
dialog.setContentView(R.layout.layout);

//layout of pop-up window is howtoplay.xml
final LayoutInflater inflater = (LayoutInflater) MainActivity.this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View popupView = inflater.inflate(R.layout.howtoplay, null, false);
final PopupWindow pw = new PopupWindow(popupView,400,440, true);


//On clicking button in dialog,popup opens
Button howto = (Button) dialog.findViewById(R.id.rules);
howto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pw.setContentView(inflater.inflate(R.layout.howtoplay, null, false));
            pw.showAtLocation(v, Gravity.CENTER, 0, 0);
            pw.update(0,0,wth*8,ht*10);

            Button close = (Button)pw.getContentView().findViewById(R.id.done);
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    pw.dismiss();

                }
            });

        }
    });

我想在单击howtoplay弹出屏幕中的按钮时打开弹出屏幕(playvideo.xml)。以下是我在按钮的onclicklistener方法中编写的代码。

public void howtoplayvideo(View v){
    System.out.println("------clicked-------");
    final LayoutInflater inflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View popupView = inflater.inflate(R.layout.playvodeo, null, false);
    final PopupWindow pw = new PopupWindow(popupView,400,440, true);
    pw.setContentView(inflater.inflate(R.layout.playvideo, null, false));
    pw.showAtLocation(v, Gravity.CENTER, 0, 0);
    pw.update(0,0,wth*8,ht*10);
}

"点击"正在打印,但后来又出现异常

Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W@453afa80 is not valid; is your activity running?

请帮助我!!

1 个答案:

答案 0 :(得分:0)

这可能为时已晚,但您的代码无效的原因是因为您说:

  

pw.showAtLocation(v,Gravity.CENTER,0,0);

您传入的v是howto按钮的视图,而不是您希望弹出窗口显示在您的布局视图之上。