android java.lang.IllegalStateException: You can not set Dialog's OnCancelListener or OnDismissListener
时间: 2024-04-12 11:27:03 浏览: 144
The `java.lang.IllegalStateException` with the message "You can not set Dialog's OnCancelListener or OnDismissListener" typically occurs when you try to set an `OnCancelListener` or `OnDismissListener` on a Dialog that has already been shown.
Both `OnCancelListener` and `OnDismissListener` are used to handle events when the dialog is canceled or dismissed, respectively. However, once a dialog has been shown, you cannot set these listeners on it anymore.
To avoid this exception, you should set the `OnCancelListener` or `OnDismissListener` before calling the `show()` method on your Dialog object. Make sure to set the listeners immediately after creating the dialog and before displaying it.
Here's an example of setting an `OnCancelListener` on an AlertDialog:
```java
AlertDialog alertDialog = new AlertDialog.Builder(context)
.setTitle("Title")
.setMessage("Message")
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// Handle onCancel event
}
})
.create();
// Set any other properties or listeners
alertDialog.show();
```
By following this approach, you should be able to avoid the `IllegalStateException` related to setting a Dialog's `OnCancelListener` or `OnDismissListener`.
阅读全文