Androidで独自のダイアログを作成する(公式ドキュメントでキャッチ)

ダイアログをandriodで作成することにしました。 公式文書から知識を得た。 しかし、判明したように、キャッチがあります。 ドキュメント「 カスタムダイアログの作成」の推奨事項に従うと、常にエラーが発生します。

Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

エラーの原因は次のとおりです。

@Override
protected Dialog onCreateDialog(int id) {
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);

dialog.setContentView(R.layout.quicklog);
dialog.setTitle("Custom Dialog");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");

return dialog;
}


理由は、間違ったコンテキストがDialogオブジェクトコンストラクターに渡されるためです。

Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);


簡単に修正できます。 getApplicationContext()this変更しthis

Dialog dialog = new Dialog(this);


この不正確さは後のドキュメントで修正されると思いますが、注意してください。

Source: https://habr.com/ru/post/J77870/


All Articles