I'm trying to make a custom dialog, following the tutorial on the Android developer site, but it crashes every time I try to show the dialog. Here's my code:
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
dialog.show();
And here's my XML for the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/btnConfirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add text"
android:layout_below="@+id/txtNewText"
android:layout_alignParentLeft="true">
</Button>
<EditText
android:id="@+id/txtNewText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true">
</EditText>
</RelativeLayout>
The custom dialog uses DIALOG to create custom alert in android studio. Dialog display a small window i.e a popup which draws the user attention over the activity before they continue moving forward. The dialog appears over the current window and display the content defined in it.
This example demonstrate about how to make custom dialog in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
If you want a custom layout in a dialog, create a layout and add it to an AlertDialog by calling setView() on your AlertDialog. Builder object. By default, the custom layout fills the dialog window, but you can still use AlertDialog. Builder methods to add buttons and a title.
You can use a custom dialog box to perform various functions: prompt a user for input, such as a table name, a field name, or a date range. allow a user to select from among several options. display more information than a standard message box.
Consider the pattern:
private static final int MY_DIALOG= 0;
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch(id) {
case MY_DIALOG:
dialog= getInstanceMyDialog();
break;
default:
dialog = null;
}
return dialog;
}
private Dialog getInstanceMyDialog() {
final Dialog d= new Dialog(this); //<=====THIS
d.setContentView(R.layout.custom_dialog);
d.setTitle("Custom Dialog");
return d;
}
JAL
This worked for me: problem-creating-a-custom-dialog
Use this instead of getApplicationContext() when instantiating the dialog:
Dialog dialog = new Dialog(this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With