دیالوگ هشدار در اندروید یک پنجره ی کوچک است که به کاربر پیشنهاد می کند در مورد چیزی تصمیم بگیرد یا چیزی را وارد کند.

بعضی اوقات در برنامه ی خود اگر از یوزر خود بخواهید تصمیمی بگیرد و گزینه بله یا خیر را انتخاب کند که یا عمل خاصی انجام شود و یا در همان برنامه باقی بماند، می توانید از دیالوگ هشدار در اندروید استفاده کنید.

برای ساختن یک دیالوگ هشدار لازم است که آبجکتی از AlertDialogBuilder با یک گروه داخلی AlertDialog بسازید. ترکیب آن در زیر ارائه شده است.

 

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

اکنون شما باید دکمه ی مثبت (yes) یا منفی (no) را با استفاده از آبجکت کلاس AlertDialogBuilder تنظیم کنید. ترکیب آن در زیر ارائه شده است.

 

alertDialogBuilder.setPositiveButton(CharSequence text, 
   DialogInterface.OnClickListener listener)
alertDialogBuilder.setNegativeButton(CharSequence text, 
   DialogInterface.OnClickListener listener)

 

علاوه بر این می توانید از عملکردهای ارائه شده توسط گروه سازنده استفاده کنید تا دیالوگ هشدار را به دلخواه خود بسازید. این عملکردها در زیر ارائه شده اند.

شماره نوع متد و توضحات
1 setIcon(Drawable icon)

این روش آیکن جعبه ی دیالوگ هشدار را تنظیم می کند.

2 setCancelable(boolean cancelable)

این روش پراپرتی کنسل شدن یا نشدن دیالوگ را تنظیم می کند.

3 setMessage(CharSequence message) این روش پیام را برای نمایش در دیالوگ هشدار تنظیم می کند.
4
setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)

ین روش لیست آیتم هایی را که باید در دیالوگ به عنوان محتوا نمایش داده شوند، تنظیم می کند. آیتم انتخاب شده توسط شنونده اطلاع داده می شود.

5
setOnCancelListener(DialogInterface.OnCancelListener onCancelListener)

این روش کال بک را تنظیم می کند که اگر دیالوگ کنسل شود، فراخوانده می شود.

6
setTitle(CharSequence title)

این روش عنوانی را تنظیم می کند که باید دردیالوگ ظاهر شود.

پس ایجاد و تنظیم سازنده ی دیالوگ، با فراخواندن روش create() از گروه سازنده، یک دیالوگ هشدار ایجاد خواهید کرد که ترکیب آن عبارت است از:

 

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

 

این ترکیب دیالوگ هشدار ایجاد خواهد کرد و آن را روی صفحه نمایش خواهد داد.

Dialog fragment:

قبل از ورود به مثال ، باید بدانیم که fragment.Dialog fragment یک فرگمنتی است که می تواند در dialog Box یک فرگمنت را نمایش دهد.

 

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:

list dialog برای نشان دادن لیستی از آیتم ها در  dialog box استفاده می شود.
فرض کنید کاربر بخواهد لیستی از برخی آیتم ها را انتخاب کند یا روی یک آیتم از لیست چند بخشی کلیک کند ، در این حال می توانیم از list dialog استفاده کنیم :

 

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 ( دیالوگ لیست تک انتخابی):

 

این لیست برای اضافه کردن لیست تک انتخابی به dialog box استفاده می شود.

 

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();
}

مثال

مثال زیر AlertDialog را در اندروید توضیح می دهد. این مثال از سه فعالیت متفاوت برای توضیح آن استفاده می کند. دیالوگ از شما می پرسد که به سمت انجام فعالیت، انجام ندادن آن یا کنسل کردن آن بروید. برای انجام آزمایش با این مثال شما نیاز به یک دستگاه حقیقی و یا یک مقلد دارید.

مرحله توضیحات
1 شما از  Android studio برای ایجاد یک برنامه ی اندروید استفاده می کنید و آن را با نام AlertDialog تحت پکیج com.example.alertdialog قرار می دهید.
2 فایل src/MainActivity.java را تغییر دهید تا برای آغاز دیالوگ کد دیالوگ هشدار اضافه کنید.
3 فایل لی اوت XML (res/layout/activity_main.xml) را تغییر دهید و اگر لازم است مولفه ی GUI اضافه کنید.
4 یک فعالیت جدید به نام PositiveActivity ایجاد کنید و آن را با مشاهده ی src/PositiveActivity.java تایید کنید.
5 فایل لی اوت XML از آخرین فعالیت res/layout/activity_positive.xml را تغییر دهید و اگر لازم است مولفه ی GUI به آن اضافه کنید.
6 یک فعالیت جدید به نام NegativeActivity ایجاد کنید و آن را با مشاهده ی src/NegativeActivity.java تایید کنید.
7 فایل لی اوت XML از فعالیت های جدید res/layout/activity_negative.xml را تغییر دهید و اگر لازم است مولفه ی GUI اضافه کنید.
8 res/values/strings.xml را تغییر دهید تا مقادیر ثابت لازم را تعریف کنید.
9 برنامه را اجرا کنید و یک دستگاه اجرا کننده ی اندروید انتخاب کنید و برنامه را روی آن نصب کنید و نتایج را تایید کنید.

کد تغییر یافته ی src/com.example.alertdialog/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();
   }
}

 

در اینجا کد تغییر یافته  res/layout/activity_main.xml را مشاهده می کنید.

 

<?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>

 

کد Strings.xml

 

<resources>
    <string name="app_name">My Application</string>
</resources>

 

در اینجا کد پیش فرض 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>

 

اجازه بدهید اپلیکیشن  شما را اجرا کنیم. فرض می کنیم که دستگاه موبایل خود را به کامپیوتر متصل کرده اید.برای اجرای برنامه از Android studio یکی از فایل های اکتیویتی اپلیکیشن  خود را باز کرده و از نوار ابزار روی آیکون Run کلیک کنید. قبل از شروع برنامه Android studio پنجره ی زیر را برای انتخاب یک گزینه، جایی که اپلیکیشن اندروید خود را اجرا می کنید، ارائه خواهد داد.

اکنون یکی از دو گزینه را انتخاب کنید و فعالیت مربوط را مشاهده کنید که در حال بارگذاری میباشد. اگر دکمه ی مثبت را انتخاب کنید صفحه ای مانند تصویر ظاهر خواهد شد.