关闭Android中的弹出窗口

4

我有一个函数,它从菜单按钮点击调用弹出窗口。它有一个“确定”按钮来关闭弹出窗口。但是在按下按钮时onclick函数没有被启动。另外,我需要在按下返回按钮时关闭弹出窗口。

    LayoutInflater inflater = (LayoutInflater) MainActivity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.about_popup, null, false),400,440, true);

    pw.showAtLocation(lv, Gravity.CENTER, 0, 0);
    View popupView=inflater.inflate(R.layout.about_popup, null, false);
    Button close = (Button) popupView.findViewById(R.id.okbutton);
    close.setOnClickListener(new OnClickListener() {

      public void onClick(View popupView) {
        pw.dismiss();
      }
    });

谢谢

3个回答

10

目前你正在向PopupWindow传递不同的View实例,并尝试在不同的实例中查找按钮,请使用你在PopupWindow中传递的相同实例来查找按钮。更改你的代码如下:

  LayoutInflater inflater = (LayoutInflater) MainActivity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  View popupView = layoutInflater.inflate(R.layout.about_popup, null, false);
  final PopupWindow pw = new PopupWindow(popupView,400,440, true);

  pw.showAtLocation(lv, Gravity.CENTER, 0, 0);
    Button close = (Button) popupView.findViewById(R.id.okbutton);
    close.setOnClickListener(new OnClickListener() {

      public void onClick(View popupView) {
        pw.dismiss();
      }
    });

第二种方法是使用PopupWindow实例,在充气布局中再次查找当前窗口上的按钮,如下所示:
Button close = (Button) pw.findViewById(R.id.okbutton);
close.setOnClickListener(new OnClickListener() {

          public void onClick(View popupView) {
            pw.dismiss();
          }
        });

1
谢谢,我知道哪里出了问题了。 更改为 View popupView = inflater.inflate(R.layout.about_popup, null, false); - Arun

1
CustomDialogClass cdd = new CustomDialogClass(this,
                "Internet Connection Error",
                "Sorry, no internet connection.Feeds cannot be refreshed",
                "Alert");
        cdd.show();

public class CustomDialogClass extends Dialog implements
    android.view.View.OnClickListener {
String txtTitle, txtText, txtType;
Button btn;
TextView alertText;
ImageView imgVw;

public CustomDialogClass(Context context, String title, String text,
        String type) {
    super(context);
    txtTitle = title;
    txtText = text;

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.alert_layout);
    imgVw = (ImageView) findViewById(R.id.iconImgview);

    alertText = (TextView) findViewById(R.id.AlertText);
    alertText.setText(txtText);

    btn = (Button) findViewById(R.id.dismis_dialog);
    btn.setOnClickListener(this);
}

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

0

更改这个

  View popupView=inflater.inflate(R.layout.about_popup, null, false);
    Button close = (Button) popupView.findViewById(R.id.okbutton);

 Button close = (Button) pw.findViewById(R.id.okbutton);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接