4

我希望应用程序在用户按下后退按钮时显示警告消息,如果用户选择是,它将返回。我在导航图片段中。

我在堆栈溢出中搜索了很多次并尝试过:

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setTitle("Save Or Not");
    builder.setMessage("Do you want to save this? ");
    builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            /*Go back:-I dont know how*/
        }
    });
    builder.setNegativeButton("Discard",null);
    builder.show();
}

但它显示了给予者错误: 方法没有覆盖其超类中的方法

编辑:我想在导航图片段中设置 onBackPressedListener(Mobiles back button)

4

3 回答 3

4

当使用 Fragments 1.1.0(现在处于 alpha 版本)时,您可以按照提供自定义后退导航文档,其中显示如何注册一个,它允许您从 FragmentOnBackPressedCallback中注册回调:onBackPressed()

public class MyFragment extends Fragment {

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // This callback will only be called when MyFragment is at least Started.
    OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
        @Override
        public void handleOnBackPressed() {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

            builder.setTitle("Save Or Not");
            builder.setMessage("Do you want to save this? ");
            builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // Save your content
                save();
                // Then pop
                NavHostFragment.findNavController(MyFragment.this).popBackStack();
            }
            builder.setNegativeButton("Discard",null);
            builder.show();
        });
        }
    });
    requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
  }
}
于 2019-05-27T06:08:06.713 回答
3

在按钮 clicklistner 中添加此行MainActivity.super.onBackPressed(); 替换您的活动名称instedMainActivity

 builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
          dialog.dismiss();
          MainActivity.super.onBackPressed();
         //Replace your Activity name insted of MainActivity
        }
    });
于 2019-05-27T04:49:43.483 回答
1
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                   //Replace Your Own Action Like Adding Toast etc and Also SuperOnbackprssed or any overriden method
                    dialog.cancel();

                }
            });
于 2019-05-27T04:53:41.077 回答