Pada postingan kali ini kita akan membuat sebuah alert dialog. Tampilan nantinya akan tampak seperti gambar berikut :
Langkah-langkah membuat alert dialog di android studio
1. Buat project baru. 2. Tambahkan kode berikut pada MainActivity.java3. Edit activity_main.xml seperti berikut:
public class MainActivity extends AppCompatActivity {
private Button button;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
context = this;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Alert Dialog")
.setMessage("Membuat Alert dialog")
.setPositiveButton("Oke", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Tombol oke di klik", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Batal", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "Batal diklik", Toast.LENGTH_SHORT).show();
}
})
;
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
4. Aplikasi siap dijalankan
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:gravity="center"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</RelativeLayout>