Android-alert-dialoges

提供:Dev Guides
移動先:案内検索

Android-アラートダイアログ

'_ダイアログは、ユーザーに決定を促すか、追加情報を入力する小さなウィンドウです。_

アプリケーションで、ユーザーが行った特定のアクションに応じて、同じアクティビティを維持し、画面を変更せずに、yesまたはnoのどちらを選択するかをユーザーに尋ねたい場合、アラートダイアログを使用できます。

アラートダイアログを作成するには、AlertDialogの内部クラスであるAlertDialogBu​​ilderのオブジェクトを作成する必要があります。 その構文は以下のとおりです

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

次に、AlertDialogBu​​ilderクラスのオブジェクトを使用して、ポジティブ(yes)またはネガティブ(no)ボタンを設定する必要があります。 その構文は

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

これとは別に、ビルダークラスが提供する他の関数を使用して、アラートダイアログをカスタマイズできます。 これらは以下にリストされています

Sr.No Method type & description
1

setIcon(Drawable icon)

このメソッドは、アラートダイアログボックスのアイコンを設定します。

2

setCancelable(boolean cancel able)

このメソッドは、ダイアログをキャンセルできるかどうかのプロパティを設定します

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

これにより、アラートダイアログが作成され、画面に表示されます。

ダイアログフラグメント

例に入る前に、ダイアログフラグメントを知る必要があります。ダイアログフラグメントは、ダイアログボックスにフラグメントを表示できるフラグメントです。

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

リストダイアログ

ダイアログボックスにアイテムのリストを表示するために使用されていました。たとえば、ユーザーがアイテムのリストを選択するか、アイテムの複数のリストからアイテムをクリックする必要があると仮定します。この場合、リストダイアログを使用できます。

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

単一選択リストダイアログ

これは、ダイアログボックスに単一の選択リストを追加するために使用されていました。ユーザーの選択に応じて、オンまたはオフにすることができます。

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

次の例は、AndroidでAlertDialogを使用する方法を示しています。

この例を試すには、エミュレータまたは実際のデバイスでこれを実行する必要があります。

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.
*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();
   }
}
*res/layout/activity_main.xml* の変更されたコードは次のとおりです。

'_以下のコードで abc はfinddevguides.comのロゴを示します_

<?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="finddevguides"
      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モバイルデバイスをコンピューターに接続していると思います。 Androidスタジオからアプリを実行するには、プロジェクトのアクティビティファイルの1つを開き、ツールバーの[画像を実行:/android/images/eclipse_run.jpg [Eclipse Run Icon]アイコンをクリックします。 アプリケーションを開始する前に、] Android Studioは次のウィンドウを表示して、Androidアプリケーションを実行するオプションを選択します。

Androidカメラチュートリアル

オプションを選択してクリックします。 たとえば、「はい」ボタンをクリックした場合、結果は次のようになります

Androidカメラチュートリアル

ボタンをクリックしないと、finish()が呼び出され、アプリケーションが閉じられます。