課題
ダイアログの中で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();
ダイアログの中のアイテムを押した時、Snackbarは出るがDialogの下にある
解決
アイテムを押すと、Dialogの中にSnackbarが出ます。ちなみにSnackbarにアクションを設定しておけば直接押すことができます(以前のようにDialogの下に出てると、Dialogを消さないとSnaackbarのボタンに触れなかった)。
Snackbarが出る時にDialogがちょっと膨らんで動くが妥協範囲内。
ポイント
SnackbarをDialogの上に出すには、Dialogに自作Viewを設定してそこに紐づける必要がある(android - Can I display material design Snackbar in dialog? - Stack Overflow)
AlertDialogを閉じるには、
AlertDialog.dismiss()
を呼び出す必要がある(http://android-note.open-memo.net/sub/dialog__dialog_clear.html)setSingleChoiceItems
の機能までViewに実装するのは大変→左下の閉じるボタンだけ実装するcoordinatorLayout
のgravity
をstart
に設定。ボタンはbackground
透明、textColor="@color/design_default_color_primary"
にして一般のDialogのものと形を揃えた
そして
- 自作したViewをinflateで設定(
final View v
) - AlertDialogを
dialog = ....create()
までする SingleChoiceItems
のOnClickListener
で出すSnackbarは先ほど設定したv
に紐づけるv
の中のボタンandroid:id="@+id/dialog_button"
のonClickでdialog.dismiss()
をするようにする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.