片段后退按钮,按两次按钮关闭应用程序

时间:2014-09-30 14:48:31

标签: java android mobile

我有片段[0],[1],[2],[3],[4]和[5]。

我想在每个片段上实现后退按钮以返回主片段。在主片段中,我希望能够在退出程序之前按两次后退按钮。

截至目前为止已经两次回击,但它适用于所有碎片。当按下应用程序关闭的任何片段时,它不会返回主片段。  我希望该函数仅用于处理主片段。

这是我的主要片段活动的代码。

private static long back_pressed; 
private Toast toast;
@Override
public void onBackPressed()
{ 


    if (back_pressed + 2000 > System.currentTimeMillis()) 
        {

             // need to cancel the toast here
         toast.cancel();  

         // code for exit
         Intent intent = new Intent(Intent.ACTION_MAIN);
             intent.addCategory(Intent.CATEGORY_HOME);
             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             startActivity(intent);

        }
        else 
        {
        // ask user to press back button one more time to close app 
        toast=  Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT);  
        toast.show();
        }
        back_pressed = System.currentTimeMillis();
}

2 个答案:

答案 0 :(得分:0)

尝试这种方式:

创建公共变量int counter = 0,并在onBackPressed中放入counter ++。在那之后把if(counter == 2){....}

    public int counter = 0;

    @Override
    public void onBackPressed()
    { 
        counter++;
        if(counter == 2){
        do something....}

    }

答案 1 :(得分:0)

尝试检查当前可见的片段是否是您的主片段。要做到这一点

final MyFragment fragment = getFragmentManager().findFragmentByTag(myFragmentTag);
if (fragment.isVisible()) {
    //...
} else {
    //...
}