如何应用片段中按下的后退按钮

时间:2015-12-05 06:32:50

标签: java android android-fragments onbackpressed

我是android的新手。我无法处理onBackPressed方法。我有一个Activity类,它有四个片段,如A,B,C,D。当我默认启动Activity时,片段A处于活动状态,片段A上有链接以移动另一个片段。我想要从片段A移动另一个片段如B,C,D并按下后退按钮它返回到片段A,如果我从片段A按下后退按钮它会显示一个对话框。 我使用onBackPressed(),如下面的

public void onBackPressed() {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            MainActivity.this);

    // set title
    alertDialogBuilder.setTitle("Exit");

    // set dialog message
    AlertDialog.Builder builder = alertDialogBuilder
            .setMessage("Do you really want to exit?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, close
                    // current activity
                    MainActivity.this.finish();
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}

但它适用于所有片段,我只想工作片段A

6 个答案:

答案 0 :(得分:1)

您必须仅在活动的onBackPressed中处理此类要求。我通常遵循以下方法:

我保留一个包含所有片段的枚举和一个跟踪当前片段的参数:

enum FRAGMENTS{
    fragmentA, fragmentB, fragmentC, fragmentD
}
FRAGMENTS mCurrentFragment;

现在更改片段的逻辑应该是:

public void changeFragment(FRAGMENTS newFragment){
    //Your logic
    mCurrentFragment = newFragment;
}

最后逻辑onBackPressed:

onBackPressed{
     if(mCurrentFragment == FRAGMENTS.fragmentA){
          //Your code here of asking the user if he/she really wants to quit
          super.onBackPressed();
     }else{
          changeFragment(getPreviousFragment(mCurrentFragment));
     }
}

如果您不想使用enum,您可以使用final int或任何其他字符串值来表示不同的片段,并使用mCurrentFragment参数来跟踪当前正在显示的片段,然后您可以轻松地使用您的Activity中的代码#39; s onBackPressed方法

如果您需要更多说明,请与我们联系。

答案 1 :(得分:1)

在替换

时将片段添加到backStack
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

然后在Activity

中覆盖onBackPressed方法

答案 2 :(得分:1)

所以这是您正在寻找的答案:)

方法1

 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {

        // Your stuff here
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

        // set title
        alertDialogBuilder.setTitle("Exit");

        // set dialog message
        AlertDialog.Builder builder = alertDialogBuilder.setMessage("Do you really want to exit?")
                .setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked, close
                        // current activity

                        System.exit(0);
                    }
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();

    }


}

//如果您遇到任何问题,请告诉我

方法2

或者在您的情况下只需将此方法粘贴到您的主要活动中,这样您也可以按照自己的意愿实现它:)

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

    // set title
    alertDialogBuilder.setTitle("Exit");

    // set dialog message
    AlertDialog.Builder builder = alertDialogBuilder.setMessage("Do you really want to exit?").setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, close
                    // current activity

                    System.exit(0);
                }
            }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();

}

答案 3 :(得分:1)

如果要覆盖onBack按下的方法,请在onActivityCreated()方法中添加此代码

getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                      getFragmentManager().popBackStack();
                    return true;
                }
                return false;
            }
        });

答案 4 :(得分:0)

使用以下代码希望它有所帮助。

//Always replace/add your fragment with a tag so that you can use that tag in future

     Fragment fr = getSupportFragmentManager().findFragmentByTag("Fragment_Name");//Fragment Name is a tag to identify fragment
     if (fr == null) {
     getSupportFragmentManager().beginTransaction()
     .replace(R.id.frame_container, new Demo_Fragment(), "Fragment_Name").commit();
     }

    //Now override onBackPressed method in MainActivity Only no need to do it in Fragment Class
    @Override
     public void onBackPressed() {
     Fragment fr = getSupportFragmentManager().findFragmentByTag("FragmentA");
    if(fr==null)
    //replace FragmentA
    else
    //Show Alert Box
     }

答案 5 :(得分:0)

为此您需要执行以下操作

在BaseFragment或Activity上创建保存当前片段对象的方法

public Fragment getCurrentFragment() {
        return currentFragment;
    }

并创建一个返回当前片段对象的方法

getCurrentFragment

现在只需要调用if (getCurrentFragment() instanceof AFragment) { showAlert } else { super.onBackPressed() } 方法并检查片段是否是A片段的实例

lxml.html.fromstring