Sometimes in AlertDialog, there is a need to get input from the user or customize it according to our requirements. So we create custom AlertDialogs. This post will show how to customize the AlertDialogs and take input from it.
AlertDialogBelow is the step-by-step implementation of the above approach:
Add the below code in custom_layout.xml. This code defines the alert dialog box dimensions and adds an edit text to it.
edit text<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@id/root" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="showAlertDialogButtonClicked" android:text="Show Dialog" /> </LinearLayout> |
import android.os.Bundle;import android.view.View;import android.widget.EditText;import androidx.appcompat.app.AlertDialog;import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void showAlertDialogButtonClicked(View view) { // Create an alert builder AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Name"); // Set the custom layout final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null); builder.setView(customLayout); // Add a button builder.setPositiveButton("OK", (dialog, which) -> { // Send data from the AlertDialog to the Activity EditText editText = customLayout.findViewById(R.id.editText); sendDialogDataToActivity(editText.getText().toString()); }); // Create and show the alert dialog AlertDialog dialog = builder.create(); dialog.show(); } // Handle the data from the AlertDialog private void sendDialogDataToActivity(String data) { Toast.makeText(this, data, Toast.LENGTH_SHORT).show(); }} |
In this lesson, we will delve into creating an Android AlertDialog in a Kotlin application. The AlertDialog class in Android is a dialog window that prompts the user for a response or to make a decision. Let's break down the essential steps involved.
By following these steps and understanding the key components, you can effectively create and work with AlertDialogs in your Android Kotlin applications.