おはやし日記

テーマ……バイク←プログラミング←旅

AlertDialogとSnackbarの合わせ技

課題

ダイアログの中でSingleChoiceItemsをクリックした時にSnackbarをDialogの上に出したい

現状

だいたいこんな感じ

String[] strings = new String[]{"hoge", "fuga", "piyo"};
new AlertDialog.Builder(this)
                .setTitle("Before")
                .setSingleChoiceItems(strings, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Snackbar.make(findViewById(R.id.coordinator), strings[i]+" was selected", Snackbar.LENGTH_SHORT).show();
                    }
                })
                .setNeutralButton("閉じる",null).show();

f:id:o-treetree:20210410042841p:plain

ダイアログの中のアイテムを押した時、Snackbarは出るがDialogの下にある

解決

androidDialogSnackbar

f:id:o-treetree:20210410043722p:plain

アイテムを押すと、Dialogの中にSnackbarが出ます。ちなみにSnackbarにアクションを設定しておけば直接押すことができます(以前のようにDialogの下に出てると、Dialogを消さないとSnaackbarのボタンに触れなかった)。

Snackbarが出る時にDialogがちょっと膨らんで動くが妥協範囲内。

ポイント

そして

  1. 自作したViewをinflateで設定(final View v
  2. AlertDialogをdialog = ....create()までする
  3. SingleChoiceItemsOnClickListenerで出すSnackbarは先ほど設定したvに紐づける
  4. vの中のボタンandroid:id="@+id/dialog_button"のonClickでdialog.dismiss()をするようにする
  5. dialog.show()

おわり

Snackbarをスワイプした時にログに下記のエラーが出るが、一応動いているのでヨシ!

E/ViewDragHelper: Ignoring pointerId=0 because ACTION_DOWN was not received for this pointer before ACTION_MOVE. It likely happened because  ViewDragHelper did not receive all the events in the event stream.
E/ViewDragHelper: Ignoring pointerId=-1 because ACTION_DOWN was not received for this pointer before ACTION_MOVE. It likely happened because  ViewDragHelper did not receive all the events in the event stream.
プライバシーポリシー ・お問い合わせはこちら