繁体   English   中英

如何在alertDialog(Android Studio)中调用活动的超类方法

[英]how to call a method of superclass of an activity in alertDialog (Android studio)

当在特定片段上的设备中点击“返回”按钮时,我想提醒用户并让他们决定隐藏应用程序还是留下来。 这里的代码段:

@Override
public void onBackPressed() {
  Fragment f = getSupportFragmentManager().findFragmentById(R.id.container);
    if(f instanceof PlanListFragment){
        builder.setPositiveButton(R.string.alert_Cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Do nothing
            }
        });
        builder.setNegativeButton(R.string.alert_OK, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
               // I want to call this: **super.onBackPressed()**; but super is not recognized at all here.
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }else{
       super.onBackPressed();
    }
}

如上所述,单击“确定”按钮时如何调用此“supper.onBackPressed()”方法?

提前致谢!

肖恩

无法识别 super.onBackPressed,因为您当前正在构建 DialogInterface.OnClickListener。 您可以在构造所述侦听器之前简单地声明一个变量 myActivity 并在该侦听器上调用 onBack 。

Activity activity = this; 
 builder.setNegativeButton...
{
      ...
      activity.onBackPressed();
      ... 
 }

用您所在的任何片段替换“活动”。

//更新

可以编写一个执行 super.onBackPressed() 调用的新方法。

正如DerDingens在她的回答中所说,由于您当前正在构建 DialogInterface.OnClickListener,因此无法识别 super.onBackPressed。

如果您仍然在同一个活动中,您可以调用 ActivityName.super.onBackPressed()。 这只会调用 super 方法。

示例:

builder.setPositiveButton(strExit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                CallActivity.super.onBackPressed();
            }
        });
@Override
public void onBackPressed(){
    if (condition == true){

        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setCancelable(true);
        dialog.setTitle("Unsaved data");
        dialog.setMessage("You'll lose any unsaved data");

        dialog.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                goBack();
            }
        });

        dialog.setNegativeButton("Cancel", null);
        dialog.create().show();

    }else{
        goBack();
    }
}
private void goBack(){ 
    super.onBackPressed(); 
}

我今天早些时候这样做了,这似乎工作得很好。 我不确定它是否应该,但确实如此。

暂无
暂无

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

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