2

Как сделать так, чтобы при открытии BottomSheetDialog появлялась клавиатура и над ней сам диалог? И EditText сразу становился активным.

Сейчас у меня диалог показывается вот так: введите сюда описание изображения введите сюда описание изображения

А хочется как здесь: введите сюда описание изображения

Вот мой код:

abstract class CustomDialog(@LayoutRes layout: Int) : DialogFragment() {
    val layoutDialog = layout
    val dialogView: View? by lazy { View.inflate(activity, layout, null) as ViewGroup }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return dialogView
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val bottomSheetDialog = BottomSheetDialog(requireActivity(), R.style.BottomSheetDialogTheme)
        val bottomSheetView = LayoutInflater.from(context).inflate(layoutDialog, null)
        bottomSheetDialog.setContentView(bottomSheetView)

        return bottomSheetDialog
    }
}

class CreateTaskDialog() : CustomDialog(R.layout.dialog_add_task) {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }
}

Вот я показываю диалог:

requireActivity().showDialog(CreateTaskDialog())

fun FragmentActivity.showDialog(dialog: DialogFragment, tag: String? = null)
        = dialog.show(this.supportFragmentManager, tag)

Стиль диалога:

<style name="BottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog">
    <item name="bottomSheetStyle">@style/BottomSheetStyle</item>
</style>

<style name="BottomSheetStyle" parent="Widget.Design.BottomSheet.Modal">
    <item name="android:windowIsFloating">false</item>
    <item name="android:windowSoftInputMode">adjustResize</item>
    <item name="android:background">@android:color/transparent</item>
</style>
1

1 ответ 1

1

Решение оказалось неочевидным) Я перерыл весь stackoverflow в том числе и англоязычный. Нашел несколько вариантов решений, но ни одно мне не помогало, пока я не сделал стиль следующим образом (пример сразу с закругленными краями):

<style name="BottomSheetDialogKeyboardTheme" parent="Theme.MaterialComponents.DayNight.BottomSheetDialog">
    <item name="android:windowIsFloating">false</item>
    <item name="android:windowSoftInputMode">adjustResize</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="android:background">@android:color/transparent</item>
    <item name="shapeAppearanceOverlay">@style/ShapeBottomSheetDialogKeyboard</item>
</style>

<style name="ShapeBottomSheetDialogKeyboard" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSizeTopRight">16dp</item>
    <item name="cornerSizeTopLeft">16dp</item>
    <item name="cornerSizeBottomRight">0dp</item>
    <item name="cornerSizeBottomLeft">0dp</item>
</style>

При создании фрагмента ещё добавил такой момент (хотя без него тоже работает нормально):

val bottomSheet = bottomSheetDialog.window?.decorView?.findViewById<FrameLayout>(R.id.design_bottom_sheet) as FrameLayout
val mBehavior = BottomSheetBehavior.from(bottomSheet)
mBehavior.state = BottomSheetBehavior.STATE_EXPANDED

И чтобы применить стиль с закругленными краями пришлось сделать добавить ещё такой код:

val newMaterialShapeDrawable: MaterialShapeDrawable = createMaterialShapeDrawable(requireContext(), bottomSheet)
                ViewCompat.setBackground(bottomSheet, newMaterialShapeDrawable)

fun createMaterialShapeDrawable(context: Context, bottomSheet: View): MaterialShapeDrawable {
    val shapeAppearanceModel = ShapeAppearanceModel
        .builder(context, 0, R.style.ShapeBottomSheetDialogKeyboard)
        .build()

    val currentMaterialShapeDrawable = bottomSheet.background as MaterialShapeDrawable
    val newMaterialShapeDrawable = MaterialShapeDrawable(shapeAppearanceModel)

    newMaterialShapeDrawable.initializeElevationOverlay(context)
    newMaterialShapeDrawable.fillColor = currentMaterialShapeDrawable.fillColor
    newMaterialShapeDrawable.tintList = currentMaterialShapeDrawable.tintList
    newMaterialShapeDrawable.elevation = currentMaterialShapeDrawable.elevation
    newMaterialShapeDrawable.strokeWidth = currentMaterialShapeDrawable.strokeWidth
    newMaterialShapeDrawable.strokeColor = currentMaterialShapeDrawable.strokeColor

    return newMaterialShapeDrawable
}

Весь код CustomDialog получился таким:

abstract class CustomDialogKeyboard(@LayoutRes layout: Int) : BottomSheetDialogFragment() {

    private val layoutDialog = layout
    private lateinit var mBehavior: BottomSheetBehavior<FrameLayout>

    val dialogView: View? by lazy { View.inflate(activity, layout, null) as ViewGroup }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return dialogView
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val bottomSheetDialog = BottomSheetDialog(requireActivity(), R.style.BottomSheetDialogKeyboardTheme)
        val bottomSheetView = LayoutInflater.from(context).inflate(layoutDialog, null)
        bottomSheetDialog.setContentView(bottomSheetView)

        bottomSheetDialog.setOnShowListener {
            try {
                val bottomSheet = bottomSheetDialog.window?.decorView?.findViewById<FrameLayout>(R.id.design_bottom_sheet) as FrameLayout
                mBehavior = BottomSheetBehavior.from(bottomSheet)
                mBehavior.state = BottomSheetBehavior.STATE_EXPANDED

                val newMaterialShapeDrawable: MaterialShapeDrawable = createMaterialShapeDrawable(requireContext(), bottomSheet)
                ViewCompat.setBackground(bottomSheet, newMaterialShapeDrawable)
            } catch (e: Exception) {}
        }

        return bottomSheetDialog
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.