Android tutorial for beginner part 7, Alert dialog | অ্যান্ড্রয়েড বাংলা টিউটোরিয়াল,

  • 23 April 20
  • Posted By : Admin
  • 64 Hits
  • 10 Comment

How to create Alert dialog

}

Java code

Paste below code in MainActivity.java file

package com.salam.alertdialog; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { public Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = findViewById(R.id.btn); final AlertDialog.Builder alertDialg = new AlertDialog.Builder(MainActivity.this); alertDialg.setTitle("Alert dialog!") .setMessage("This is alert dialog message.") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(MainActivity.this,"you clicked yes.", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("No ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(MainActivity.this,"you clicked no.", Toast.LENGTH_SHORT).show(); } }); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { alertDialg.show(); } }); } }

Create xml file

below xml code

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:gravity="center" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Android Alert dialog" android:textSize="40sp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btn" android:text="Show dialog" android:layout_marginTop="30dp"/> </LinearLayout>