2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Android】Dialog Fragmentの作り方

Last updated at Posted at 2019-09-10
HogeActivity.java
public class HogeActivity extends AppCompatActivity  {
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button button = findViewById(R.id.huga_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //ダイアログを表示する
              DialogFragment dialog = new DialogFragment();
              // 注意: getFragmentManager()を使用するとエラーになる
              dialog.show(getSupportFragmentManager(),"sample");
            }
        });
  }
}
DialogFragment.java
public class BookReviewDialogFragment extends DialogFragment {
    // ダイアログが生成された時に呼ばれるメソッド
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // ダイアログ生成  AlertDialogのBuilderクラスを指定してインスタンス化します
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
        // タイトル設定
        dialogBuilder.setTitle("ダイアログタイトル");
        // 表示する文章設定
        dialogBuilder.setMessage("値を入力してください");
        // 入力フィールド作成
        final EditText editText = new EditText(getActivity());
        dialogBuilder.setView(editText);
        // OKボタン作成
        dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // editTextから値を取得
                String returnValue = editText.getText().toString();
                // HogeActivityのインスタンスを取得
                HogeActivity hogeActivity = (HogeActivity) getActivity();
                hogeActivity.setTextView(returnValue);
            }
        });
        // NGボタン作成
        dialogBuilder.setNegativeButton("NG", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 何もしないで閉じる
            }
        });
        // dialogBulderを返す
        return dialogBuilder.create();
    }
}

■ ダイアログフラグメントのOKボタンの文字を@stringsから参照する

Resources res = getResources();
// OKボタン作成 dialogBuilder.setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?