2012年4月25日水曜日

Dialog

メッセージを表示するためにAlertDialogクラスや、進捗状況を示すProgressDialogクラス(STYLE_SPINNER/STYLE_HORIZONTAL)を使いました。日付や時刻を選択するDatePickerDialogクラスやTimePickerDialogクラスも使いましたね。

これらはDialogクラスを継承した派生クラスです。今回はDialogクラスを使ってメッセージを表示します。

まず、メイン画面です。

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
    <Button
        android:id="@+id/open_dialog_btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Open Dialog"
        />
</LinearLayout>
ボタンをひとつ用意しています。

DialogTest1aActivity.java
package jp.co.triware.samples.DialogTest1a;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;

public class DialogTest1aActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ((Button)findViewById(R.id.open_dialog_btn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dlg = new Dialog(DialogTest1aActivity.this);
                dlg.setTitle("Quick Brown Fox");
                dlg.setContentView(R.layout.dialog);
                dlg.show();
            }
        });
    }
}
ボタンがクリックされたら、「Quick Brown Fox」というタイトルのダイアログを表示します。ダイアログの内容はdialog.xmlです。

dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="THE QUICK BROWN FOX"
    />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="JUMPS OVER THE LAZY DOG"
    />
</LinearLayout>
ダイアログに表示する内容です。「THE QUICK BROWN FOX」と「JUMPS OVER THE LAZY DOG」を2行で表示します。

Androidプロジェクトの設定
プロジェクト名:DialogTest1a
アプリケーション名:DialogTest1a
パッケージ名:jp.co.triware.samples.DialogTest1a
アクティビティーの作成:DialogTest1aActivity
ビルドターゲットや最小SDKバージョンは、お使いの開発環境に合わせて設定してください。

実行結果
「Open Dialog」ボタンをクリックすると、右の画像のように、ダイアログが表示されました。


・・・ちょっと待ってください。dialog.xmlではTextViewの幅として「fill_parent」を指定していますね。この表示は「wrap_content」を指定したもののように見えます。

でも、どうやら現状では(少なくともAndroid 4.0までは)このような表示になってしまうようです。

だからといって横幅いっぱいに表示する方法がないわけではありません。次回はその方法をご紹介します。

0 件のコメント:

コメントを投稿