Learn how to implement custom layout in android AlertDialog. To inflate custom view in alertdialog i am using AlertDialog.Builder class to create dialog box.
Step 1. Create new project in android and add button on your main actvity.
Step 2. Create new Layout file in res folder, this is our view which we inflate in AlertDialog.
Step 3. Now open your MainActivity.java file and add OnClickListener on button and when user click on button we create popup.
Add custom layout in AlertDialog Code:
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); LayoutInflater inflater = LayoutInflater.from(getApplicationContext()); alertView = inflater.inflate(R.layout.custom_view, null); // Add your view builder.setView(alertView); builder.setTitle("Title"); builder.setIcon(R.drawable.ic_launcher); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Find objects from view EditText user = (EditText)alertView.findViewById(R.id.user); String username = user.getText().toString(); Toast toast = Toast.makeText(getApplicationContext(), "User: " + username, Toast.LENGTH_SHORT); toast.show(); } }); builder.setCancelable(false); AlertDialog myDialog = builder.create(); myDialog.show(); // Show Popup
To hide popup you call myDialog.hide().
🙂