Create Custom Android AlertDialog


Custom Android AlertDialog
Custom Android AlertDialog

AlertDialog in Android are used to display pop-up dialogs with buttons. If you want to create a custom layout for AlertDialog you need to make use of FrameLayout. We can create our custom layout XML file and add any View component we want,

File : custom_aleartdialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:hint="Enter Message"
        android:layout_margin="20dp"
        android:layout_weight="1" />
</LinearLayout>

We will inflate the custom layout that we have created to the AlertDialog using, LayoutInflater,

MainActivity.java
public class MainActivity extends ActionBarActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);




        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        builder.setTitle("Custom AlertDialog");



        builder.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this,"Get Started!",Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        });

        LayoutInflater inflater = getLayoutInflater();
        View dialoglayout = inflater.inflate(R.layout.custom_alertdialog, null);

        builder.setView(dialoglayout);
        builder.show();

    }

}



Recent Posts:




Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.