2

当用户按下后退按钮时,我想关闭一个弹出窗口。由于我处于 Fragment 的上下文中,因此我没有onBackPressed()可用的方法。

关闭弹出窗口应该不难,因为我只需要调用该dismiss()方法。问题是我不知道如何检测后退按钮的按下

我可以对片段使用类似的东西吗?或者有没有其他方法可以检测到从这个片段中按下后退按钮?

谢谢!

稍后编辑 => 我想做什么

在我的主要活动中,我实现了onBackPressed()这样的方法:

@Override
public void onBackPressed() {
    //isThePopupShowing() is a method in the target fragment which returns true if the PopupWindow is currently showing
    if (secondFragment.isThePoupShowing()) {
        // dismissPopup is a method in the same fragment which closes the PopupWindow with the dismiss() method
        secondFragment.dismissPopup();
        Log.d("DismissPopup", "And finally here!");
    } else {
        super.onBackPressed();
    }
}

当我在这里创建片段时:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.home);

    SharedPreferences user_details = getSharedPreferences(
            ro.gebs.captoom.utils.Constants.PREFS_NAME, 0);

    LoginFragment firstFragment = new LoginFragment();
    secondFragment = new HomeScreenFragment();

    String userid = user_details.getString("userid", null);

    manager = getSupportFragmentManager();

    if (userid == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, firstFragment).commit();
    } else {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, secondFragment).commit();
    }
}

这是我的片段中的代码:

public boolean isThePoupShowing() {
    return sync_popup != null && sync_popup.isShowing();
}

//
public void dismissPopup() {
    Log.d("DismissPopup", "I got here, dismissing");
    sync_popup.dismissPopup();
}

这是驳回方法:

public void dismissPopup(){
        layout.setVisibility(View.GONE);
        dismiss();
        Log.d("DismissPopup", "and in SyncQuickAction");
    }

后退按钮正常工作,因为一旦我在片段打开时按下后退按钮,应用程序就会关闭,但当我按下后退按钮时弹出窗口不会消失......关于我可能做错了什么的任何建议?

谢谢

4

2 回答 2

0

当弹出窗口显示时,片段会暂停(片段的生命周期),因此 sync_popup 获取 null 值,并且 isThePoupShowing 方法在从 Activity 调用时始终获取 false 值。

当您将popupWindow设置为静态成员时,系统不会在片段暂停时“回收”该成员,您可以正确将其关闭。

于 2013-11-04T13:04:22.647 回答
0

代替

popupWindow.setOutsideTouchable(false);

有了这个

popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
于 2016-02-27T06:31:32.893 回答