Android - 弹出窗口没有关闭

时间:2017-01-31 05:48:30

标签: android popupwindow

我想在单击按钮时关闭弹出窗口,但似乎解除功能不起作用且窗口没有关闭。我错了什么?

(我是初学者,因此代码可能很'奇怪'。请理解......)

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();
        }
    };
}

2 个答案:

答案 0 :(得分:0)

您已将弹出窗口声明为全局,并且在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);
}

答案 1 :(得分:0)

用于关闭弹出窗口的弹出窗口变量尚未在您发布的代码中初始化。您在方法内创建的最终变量是本地变量,并且在该方法之外无法访问。 因此,初始化变量或在方法中使用相同的变量。