简体   繁体   English

Android-弹出窗口未关闭

[英]Android - Popup window is not closing

I want to close the popup window when I click a button, but it seems dismiss function doesn't work and the window is not closing. 单击按钮时,我想关闭弹出窗口,但是关闭功能似乎无法正常工作,并且窗口没有关闭。 What did I wrong? 我怎么了

(I'm a beginner, so codes might be 'weird'. Please understand...) (我是一个初学者,所以代码可能很“奇怪”。请理解...)

public class AlarmPopup extends Activity {
    private PopupWindow popup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        onShowPopup();
    }

    public void onShowPopup(){
        LayoutInflater inflater = (LayoutInflater)     getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View view = inflater.inflate(R.layout.alarm_popup, null, false);
        final PopupWindow popup = new PopupWindow(view, 400, 300, true);

        setContentView(R.layout.alarm_popup);

        view.findViewById(R.id.button).post(new Runnable() {
            @Override
            public void run() {
                popup.showAtLocation(view, Gravity.CENTER, 0, 0);
            }
        });

        findViewById(R.id.button).setOnClickListener(mClickListener);
    }

    Button.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) { // dismiss and stop the alarm function on other class
            Intent i = new Intent(AlarmPopup.this, AlarmService.class);
            stopService(i); // this function is working...
            popup.dismiss();
        }
    };
}

You have declared popup as global and inside your onShowPopup you are creating new object for popup so that local popup will never be accessible from listener so make the changes as below: 您已将popup声明为全局,并且在onShowPopup内部正在创建用于弹出的新对象,以使本地弹出窗口永远无法从侦听器访问,因此进行如下更改:

public void onShowPopup(){
    LayoutInflater inflater = (LayoutInflater)     getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View view = inflater.inflate(R.layout.alarm_popup, null, false);
    popup = new PopupWindow(view, 400, 300, true);

    setContentView(R.layout.alarm_popup);

    view.findViewById(R.id.button).post(new Runnable() {
        @Override
        public void run() {
            popup.showAtLocation(view, Gravity.CENTER, 0, 0);
        }
    });

    view.findViewById(R.id.button).setOnClickListener(mClickListener);
}

Popup variable that you are using to dismiss your popup window has not been initialized in the code that you have posted. 用于发布弹出窗口的Popup变量尚未在发布的代码中初始化 Your final variable that you have created inside method is local and will not be accessible outside that method. 您在方法内部创建的最终变量是本地变量,无法在该方法外部访问。 So initialize your variable or use same variable inside method too. 因此,初始化变量或在方法内部也使用相同的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM