Dialog adalah sebuah jendela kecil yang meminta pengguna untuk mebuat keputusan atau memasukan informasi tambahan.
Kadang kala di dalam aplikasi Anda, jika kamu Anda ingin bertanya kepada pengguna tentang sebuah pilihan / keputusan antara Ya / Tidak, dan tetap berada di aktivitas yang sama, tanpa mengubah layar, maka Anda dapat menggunakan Alert Dialog.
Untuk membua Alert Dialog, Anda perlu membuat objek AlertDialogBuilder yang merupakan inner class dari AlertDialog. Berikut sintaksisnya:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
Sekarang Anda harus mengatur tombol positif (ya) atau negatif (tidak) menggunakan objek kelas AlertDialogBuilder. Sintaksnya adalah
alertDialogBuilder.setPositiveButton(CharSequence text,
DialogInterface.OnClickListener listener)
alertDialogBuilder.setNegativeButton(CharSequence text,
DialogInterface.OnClickListener listener)
Terlepas dari ini, Anda dapat menggunakan fungsi lain yang disediakan oleh kelas builder untuk menyesuaikan dialog peringatan. Sebagaimana tercantum di bawah ini.
| Sr.No | Method type & description |
|-------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 1 | setIcon(Drawable icon) This method set the icon of the alert dialog box. |
| 2 | setCancelable(boolean cancel able) This method sets the property that the dialog can be cancelled or not |
| 3 | setMessage(CharSequence message) This method sets the message to be displayed in the alert dialog |
| 4 | setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener) This method sets list of items to be displayed in the dialog as the content. The selected option will be notified by the listener |
| 5 | setOnCancelListener(DialogInterface.OnCancelListener onCancelListener) This method Sets the callback that will be called if the dialog is cancelled. |
| 6 | setTitle(CharSequence title) This method set the title to be appear in the dialog |
Setelah membuat dan mengatur pembuat dialog, Anda akan membuat dialog peringatan dengan memanggil metode create() kelas builder. Sintaksnya ini
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
Ini akan membuat dialog peringatan dan akan menampilkannya di layar.
Dialog fragment
Sebelum masuk ke sebuah contoh, kita perlu mengetahui fragmen dialog. Fragmen dialog adalah fragmen yang dapat menampilkan fragmen dalam kotak dialog
public class DialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
toast.makeText(this,"enter a text here",Toast.LENTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
});
// Create the AlertDialog object and return it
return builder.create();
}
}
}
List dialog
Ini sering digunakan untuk menunjukkan daftar item dalam kotak dialog. Anggaplah pengguna harus memilih daftar item tersebut.
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(Pick a Color)
.setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
}
});
return builder.create();
}
Single-choice list dialog
Ini telah digunakan untuk menambahkan daftar pilihan tunggal ke kotak Dialog. Kita dapat memeriksa atau menghapus centang sesuai pilihan pengguna.
public Dialog onCreateDialog(Bundle savedInstanceState) {
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("This is list choice dialog box");
.setMultiChoiceItems(R.array.toppings, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
mSelectedItems.add(which);
}
else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
...
}
});
return builder.create();
}
Contoh
Contoh berikut menunjukkan penggunaan AlertDialog di android.
Untuk bereksperimen dengan contoh ini, Anda perlu menjalankan ini pada emulator atau perangkat yang sebenarnya.
| Steps | Description |
|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------|
| 1 | You will use Android studio to create an Android application and name it as My Application under a package com.example.sairamkrishna.myapplication. |
| 2 | Modify src/MainActivity.java file to add alert dialog code to launch the dialog. |
| 3 | Modify layout XML file res/layout/activity_main.xml add any GUI component if required. |
| 4 | No need to change default string constants. Android studio takes care of default strings at values/string.xml |
| 5 | Run the application and choose a running android device and install the application on it and verify the results. |
Berikut ini adalah kode modifikasi dari src / MainActivity.java
package com.example.sairamkrishna.myapplication;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void open(View view){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure,
You wanted to make decision");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(MainActivity.this,"You clicked yes
button",Toast.LENGTH_LONG).show();
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
Berikut ini adalah modifikasi kode res / layout / activity_main.xml. Di bawah kode abc menunjukkan logo tutorialspoint
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert Dialog"
android:id="@+id/textView"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:id="@+id/textView2"
android:textColor="#ff3eff0f"
android:textSize="35dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert dialog"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_marginTop="42dp"
android:onClick="open"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />
</RelativeLayout>
Ini adalah Strings.xml
<resources>
<string name="app_name">My Application</string>
</resources>
Berikut adalah kode default AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Mari coba jalankan aplikasi Anda. Saya berasumsi Anda telah menghubungkan perangkat Android Mobile Anda yang sebenarnya dengan komputer Anda. Untuk menjalankan aplikasi dari studio Android, buka salah satu file aktivitas proyek Anda dan klik Jalankan Ikon Eclipse Run Icon dari bilah alat. Sebelum memulai aplikasi Anda,] Android studio akan menampilkan jendela berikut untuk memilih opsi di mana Anda ingin menjalankan aplikasi Android Anda.

Pilih opsi Anda dan kemudian klik di atasnya. Misalnya, jika Anda mengklik tombol YES, maka hasilnya adalah sebagai berikut

jika Anda mengklik tombol NO, maka memanggil finish() dan itu akan menutup aplikasi Anda.