To create an alert dialog in Android Studio, you can use the AlertDialog.Builder
class. Here is an example of how you can create an alert dialog in Android:
<Button android:id="@+id/button_show_alert" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Alert" />oSurce:www.lautturi.com
public class MainActivity extends AppCompatActivity { private Button buttonShowAlert; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonShowAlert = findViewById(R.id.button_show_alert); buttonShowAlert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showAlert(); } }); } private void showAlert() { // Create an alert dialog builder AlertDialog.Builder builder = new AlertDialog.Builder(this); // Set the alert dialog title and message builder.setTitle("Alert Dialog Title") .setMessage("This is the message of the alert dialog."); // Add a positive button to the alert dialog builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // The user clicked the OK button } }); // Create and show the alert dialog AlertDialog dialog = builder.create(); dialog.show(); } }
This code creates an AlertDialog.Builder
object and sets the title and message of the alert dialog using the setTitle
and setMessage
methods. It then adds a positive button to the alert dialog using the setPositiveButton
method and sets an OnClickListener
to handle the button click. Finally, it creates and shows the alert dialog using the create
and show
methods of the AlertDialog.Builder
class.
You can also add negative and neutral buttons to the alert dialog using the setNegativeButton
and setNeutralButton
methods, respectively. You can also customize the layout of the alert dialog by setting a custom view using the setView
method.