简体   繁体   English

按下后退按钮时如何关闭片段?

[英]How to close a fragment when back button is pressed?

I have an activity wherein if i click the "BUY" button, it will open a fragment about (150x150 pixels) to ask for the "quantity". 我有一个活动,如果我单击“购买”按钮,它将打开一个约(150x150像素)的片段,要求“数量”。 If the user will press the back button, it will just simply close the fragment. 如果用户按下后退按钮,它将仅关闭片段。 Any Ideas about closing the fragment? 关于关闭片段有什么想法吗?

You don't need to do it in a fragment it's too much for this simple use, i suggest you to use a PopupWindow: 您不需要在一个片段中进行此操作,对于此简单用途而言,它太多了,我建议您使用PopupWindow:

When you click on Buy Button, you show the popup. 当您单击“购买”按钮时,将显示弹出窗口。

PopupWindow is enough customizable to make your layout as you want PopupWindow足够可自定义,可以根据需要进行布局

here an example : https://android--code.blogspot.com/2016/01/android-popup-window-example.html 这是一个例子: https : //android--code.blogspot.com/2016/01/android-popup-window-example.html

如果您确实要使用Fragment而不是按照建议的对话框并要删除它,请在创建它时保留对其的引用,然后使用getFragmentManager().beginTransaction().remove(fragment).commit() (也可以detach如果您只想将其与活动分离而不是将其完全销毁,则可以将其移除。

Use popbackstack on backpress of activty by overriding it. 通过覆盖活动,在活动活动的背面使用popbackstack。

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 0) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

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

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