How to create a custom AlertDialog in Android
Sometimes in AlertDialog, there is need to get input from the user or customize according to our requirements. So we create custom AlertDialogs. This post will show how to customize the AlertDialogs and take the input from it.
Below is the step by step implementation of the above approach:
- Step 1: Create a XML file: custom_layout.xml. Add the below code in custom_layout.xml. This code defines the alertdialog box dimensions and add a edittext in it.
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:paddingLeft="20dp"android:paddingRight="20dp"android:layout_width="match_parent"android:layout_height="match_parent"><EditTextandroid:id="@+id/editText"android:layout_width="match_parent"android:layout_height="wrap_content"/></LinearLayout> - Step 2: Add a button in activity_main.xml. The button when clicked will show the AlertDialog box.
<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:id="@+id/root"android:orientation="vertical"tools:context=".MainActivity"><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:onClick="showAlertDialogButtonClicked"android:text="Show Dialog"/></LinearLayout> - Step 3:
Add custom_layout.xml in that activity in which you want to show custom alert dialog here it is added in MainActivity.java.
publicclassMainActivityextendsAppCompatActivity {@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}publicvoidshowAlertDialogButtonClicked(View view){// Create an alert builderAlertDialog.Builder builder=newAlertDialog.Builder(this);builder.setTitle("Name");// set the custom layoutfinalView customLayout= getLayoutInflater().inflate(R.layout.custom_layout,null);builder.setView(customLayout);// add a buttonbuilder.setPositiveButton("OK",newDialogInterface.OnClickListener() {@OverridepublicvoidonClick(DialogInterface dialog,intwhich){// send data from the// AlertDialog to the ActivityEditText editText= customLayout.findViewById(R.id.editText);sendDialogDataToActivity(editText.getText().toString());}});// create and show// the alert dialogAlertDialog dialog= builder.create();dialog.show();}// Do something with the data// coming from the AlertDialogprivatevoidsendDialogDataToActivity(String data){Toast.makeText(this,data,Toast.LENGTH_SHORT).show();}}
Output:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



