Android で再開する Java プログラミング(14) - ダイアログを制するものがAndroidを制する!
Android の AlertDialog は非常に便利です。メッセージを表示するだけでなく、リストを表示することもできるなど高機能です。ここでは、AlertDaialog の使い方を紹介します。
ダイアログを制するものが Android を制す?!
まずは、基本的な AlertDialog の使い方を紹介します。ここでは、AlertDialogText というプロジェクトを作ってみました。
package com.example.test;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
public class AlertDialogText extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// ダイアログの表示
AlertDialog.Builder dlg;
dlg = new AlertDialog.Builder(this);
dlg.setTitle("TEST");
dlg.setMessage("Hello, World!");
dlg.show();
}
}
これを実行すると、下記のように表示されます。
また、AlertDialog はメソッドチェーンを利用して、完結に記述できる仕組みも備えています。下記のように書くこともできます。
new AlertDialog.Builder(this)
.setTitle("TEST")
.setMessage("Hello, Wolrd!")
.show();
これは、setTitle() などのメソッドが、AlertDialog.Builder を戻り値として返すようになっているので、このように記述することができるのです。
OKボタンのついたダイアログ
上記の基本的なダイアログでは、[戻る]ボタンを押さないとダイアログが閉じず若干不便です。そこで、OKボタンのついたダイアログを作ってみます。
new AlertDialog.Builder(this)
.setTitle("TEST")
.setMessage("Hello, Wolrd!")
.setPositiveButton("OK", null)
.show();
これで、OK ボタンをタップすることで、ダイアログを閉じることができます。
メッセージやラベルを国際化する場合
ちなみに、ボタンのラベルや各種メッセージなどを国際化する場合には、リソースXMLを編集した上で、R.string.xxx のようなリソースIDを指定することで実現できます。
手順としては、Eclipse の Pacakge Explorer の<res>ディレクトリにある<values>と同じ構造の、<values-ja> というディレクトリを作ります。
- values\strings.xml に <string name="label_ok">OK</string> を追加
- values-ja\strings.xml に <string name="label_ok">おっけー</string> を追加
new AlertDialog.Builder(this)
.setTitle("TEST")
.setMessage("Hello, Wolrd!")
.setPositiveButton(R.string.label_ok, null) // ←国際化
.show();
すると、以下のように、日本語環境では、日本語のリソースが適用されます。
Yes/Noで質問するダイアログ
次に、Yes/No で質問するダイアログを作ってみます。この場合、setPositiveButton() と setNegativeButton() メソッドを利用して、ボタンのラベルとボタンが押された時の処理を記述します。
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("YES/NO Dialog")
.setMessage("Is this a pen ?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* ここにYESの処理 */
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* ここにNOの処理 */
}
})
.show();
Yes/No/Cancelで質問するダイアログ
Yes/No/Cancel で質問する場合には、上記の2つに加えて、setNeutralButton() メソッドを呼ぶことで実現できます。
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("YES/NO Dialog")
.setMessage("Is this a pen ?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* ここにYESの処理 */
}
})
.setNeutralButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* ここにNOの処理 */
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* ここにCancelの処理 */
}
})
.show();
リストダイアログ
リストダイアログを使うと、選択肢から候補を1つ選ぶことができます。
String[] str_items = {"Red","Green","Blue"};
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("Please Select Color")
.setItems(str_items, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
new AlertDialog.Builder(AlertDialogText.this)
.setTitle("which=" + which)
.show();
}
})
.show();
実行すると以下のように表示されます。
項目をタップするとインデックスを表示します。どの位置をタップしたのかインデックスを返すので、元の String[] の値をリソースに指定するか、アクセス可能な変数に代入しておく必要があるでしょう。
ラジオボタン・ダイアログ
ラジオボタンが並んだダイアログを作るには、setSingleChoiceItems() メソッドに、選択肢のString[]と、初期値、イベントを指定します。
package com.example.test;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
public class AlertDialogText extends Activity {
String[] str_items = {"Red","Green","Blue"};
String result_item = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// set default value
int def_index = 2;
result_item = str_items[def_index];
// Single Choice Dialog
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("Please Select Color")
.setSingleChoiceItems(str_items, def_index,
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
result_item = str_items[which];
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* OKボタンをクリックした時の処理 */
new AlertDialog.Builder(AlertDialogText.this)
.setTitle("color=" + result_item)
.show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* Cancel ボタンをクリックした時の処理 */
new AlertDialog.Builder(AlertDialogText.this)
.setTitle("Canceled")
.show();
}
})
.show();
}
}
チェックボックス・ダイアログ
複数のアイテムを選択するチェックボックスダイアログは次のように使うことができます。アイテムラベルの一覧 String[] と、チェックしたかどうかを表す boolen[] の2つを引数に指定することになっています。アイテムの変更を監視するのは、 OnMultiChoiceClickListenerの中の onClick()イベントです。
package com.example.test;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
public class AlertDialogText extends Activity {
String[] str_items = {"Cake","Banana","Tea","coffee"};
boolean[] flags = {true,false,true,false};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Multi Choice Dialog
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("何を食べますか?")
.setMultiChoiceItems(str_items, flags,
new DialogInterface.OnMultiChoiceClickListener(){
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
flags[which] = isChecked;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* OKボタンをクリックした時の処理 */
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* Cancel ボタンをクリックした時の処理 */
}
})
.show();
}
}
カスタムダイアログ
ダイアログに、コンポーネントを載せれば、自由なカスタムダイアログを作ることができます。以下は、テキスト入力が可能な EditText コンポーネントを setView() メソッドを使って載せています。これにより、テキスト入力が可能なダイアログを表示することができます。
package com.example.test;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.EditText;
public class AlertDialogText extends Activity {
public EditText edtInput;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create EditText
edtInput = new EditText(this);
// Show Dialog
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("何を食べますか?")
.setView(edtInput)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* OKボタンをクリックした時の処理 */
new AlertDialog.Builder(AlertDialogText.this)
.setTitle("食べるもの: " + edtInput.getText().toString())
.show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* Cancel ボタンをクリックした時の処理 */
}
})
.show();
}
}
実行してみると、テキストを入力できます。
入力したテキストを取得できるようにするには、EditText をアクセス可能な位置で宣言しておきます。
プログレスダイアログ
途中経過を表示するプログレスバーのついたダイアログがあります。ファイルのダウンロード経過を表示したり、ちょっとした処理の経過を表すのに便利です。
package com.example.test;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.EditText;
public class AlertDialogText extends Activity {
public ProgressDialog progDlg;
public Handler progHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// プログレスダイアログを作成して表示
progDlg = new ProgressDialog(this);
progDlg.setIcon(R.drawable.icon);
progDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progDlg.setMax(100);
progDlg.setButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton) {
progDlg.cancel();
}
});
// プログレスバーを動かす
progHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
int v = progDlg.getProgress();
if (v >= 100) {
progDlg.dismiss();
} else {
progDlg.incrementProgressBy(1);
progHandler.sendEmptyMessageDelayed(0, 100);
}
}
};
// OK をクリックしたらダイアログを表示する
new AlertDialog.Builder(this)
.setTitle("PUSH START BUTTON")
.setPositiveButton("START", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
progDlg.show();
progHandler.sendEmptyMessage(0);
}
})
.show();
}
}
まとめ
以上、android に備わっている便利なダイアログの使い方をまとめてみました。かなり豊富なダイアログのバリエーションがあることや、なんでも配置できるカスタムダイアログがあるので、かなり便利だと感じました。実際に何か作るときの参考にしてみてください。
このサイトについて
TrackBack URL :













3
Posted by t | 2009年11月09日 11:54
y
Posted by t | 2009年11月09日 11:54
test!
Posted by t | 2009年11月09日 11:55
[…] その他、リストから選択させたりチェックボックスから選択させたりもできます。 八角研究所 : Android で再開する Java プログラミング(14) – ダイアログ… […]
Posted by はじめてのAndroidアプリ開発 – アラートダイアログ編 | もさてん備忘録 | 2010年07月25日 12:21
はじめてのAndroidアプリ開発 – アラートダイアログ編…
アラートダイアログ表示方法の備忘録です。 環境 Windows Vista Home Premium SP1 Eclipse 3.6.0 Android SDK 2.2 手順 package com.mosa10.alert.com.mosa10; import com.mosa10.alert.R; import android.app.Activity; import android.app.Aler…
Posted by もさてん備忘録 | 2010年07月27日 23:00