对话问题:在添加内容之前必须调用requestFeature()

fre*_*ley 16 android dialog

我正在创建一个包含EditText的自定义对话框,以便我可以从用户那里获取文本数据:

final EditText newKey = (EditText) findViewById(R.id.dialog_result);
AlertDialog.Builder keyBuilder = new AlertDialog.Builder(StegDroid.this);
keyBuilder
.setCancelable(false)
.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
        Log.v("Dialog","New Key: "+newKey.getText().toString());
    }
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
       }
   });
AlertDialog dialog = keyBuilder.create();
dialog.setTitle("Decryption Failed");
dialog.setContentView(R.layout.decrypt_failed_dialog);
dialog.show();
Run Code Online (Sandbox Code Playgroud)

但是我总是得到这个例外:

01-11 18:49:00.507: ERROR/AndroidRuntime(3461): android.util.AndroidRuntimeException: requestFeature() must be called before adding content
01-11 18:49:00.507: ERROR/AndroidRuntime(3461):     at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:181)
01-11 18:49:00.507: ERROR/AndroidRuntime(3461):     at com.android.internal.app.AlertController.installContent(AlertController.java:199)
01-11 18:49:00.507: ERROR/AndroidRuntime(3461):     at android.app.AlertDialog.onCreate(AlertDialog.java:251)

...
Run Code Online (Sandbox Code Playgroud)

在线dialog.show().我应该怎么做才能摆脱这个?

Cri*_*ian 37

您需要在创建对话框之前设置自定义视图.此外,您需要使用setView(View)而不是setContentView()使用由您提供的默认正面和负面按钮AlertDialog.

final EditText newKey = (EditText) findViewById(R.id.dialog_result);
AlertDialog.Builder keyBuilder = new AlertDialog.Builder(StegDroid.this);
keyBuilder
.setCancelable(false)
.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
        Log.v("Dialog","New Key: "+newKey.getText().toString());
    }
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
       }
   });
keyBuilder.setTitle("Decryption Failed");
keyBuilder.setView(getLayoutInflater().inflate(R.layout.decrypt_failed_dialog, null));
AlertDialog dialog = keyBuilder.create();
dialog.show();
Run Code Online (Sandbox Code Playgroud)

  • 添加评论会很好,这样其他人就可以轻松地找出不同的方式,而无需比较代码. (3认同)
  • 谢谢!你用"......你需要使用setView(View)而不是setContentView()..."来节省我的一天.":) (3认同)

moh*_*abi 7

我的应用程序中有一个警报对话框,它曾经在 android API 23 上给我这个 android 运行时异常。

原来这个问题与导入有关。我改为android.app.AlertDialog导入androidx.appcompat.app.AlertDialog,问题就解决了。

这适用于使用 AndroidX Artifacts 的项目。android.support.v7.app.AlertDialog如果您不使用 AndroidX,请考虑使用支持版本。


Ric*_*ket 5

还要确保您没有返回一个已经显示的对话框。例如,ProgressDialog有一个方便的静态方法show(),它接受一些参数并返回一个ProgressDialog. 事实证明您不能使用该方法并返回结果ProgressDialog,因为当操作系统尝试显示它(并且它已经显示)时,它会抛出相同的异常。

还要注意:上述行为在 Android 模拟器上出现过,但实际上并没有抛出异常,并且在运行 2.2 的 Droid Incredible 上运行良好。