【Android】DialogFragmentの基本

2019年7月29日

DialogFragmentの使い方です。
今までは「Activity.showDialog」を使用していましたが、APIレベル13で非推奨となりました。
これからはDialogFragmentを使用して、ダイアログを表示することになります。

1.DialogFragmentのクラスを作る

今回は、簡単な「はい」「いいえ」のダイアログを作成してみます。

TestDialogFragment.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
public class TestDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("テストダイアログ")
                .setPositiveButton("はい", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // クリック時の処理
                    }
                })
                .setNegativeButton("いいえ", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // クリック時の処理
                    }
                });
        return builder.create();
    }
}

2.ダイアログを表示する

DialogFragmentのインスタンスを作成し、「show」で表示します。
下記例「show」の"test1″は、フラグメントの状態を保存して、復元する時に使用するタグ名になります。「findFragmentByTag()」を呼び出すことでフラグメントのインスタンスを取得できます。

MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
import android.os.Bundle;
import android.app.Activity;
import android.app.DialogFragment;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // ダイアログを表示する
        DialogFragment newFragment = new TestDialogFragment();
        newFragment.show(getFragmentManager(), "test1");
    }
}

参考:Androidデベロッパーサイト

スポンサーリンク