键盘遮挡了BottomSheetDialogFragment

39

当我更新了支持库时,键盘下方出现了更多字段。我知道它是Kotlin,但它几乎看起来和Java一样。如何解决这个问题?

这就是它的样子:

输入图像描述

我的代码:

class ProjectsEditBottomSheetFragment(val privateID: String,
                                  val publicID: String) : BottomSheetDialogFragment() {



private val mBottomSheetBehaviorCallback = object : BottomSheetBehavior.BottomSheetCallback() {
    override fun onStateChanged(bottomSheet: View, newState: Int) {
        if (newState == BottomSheetBehavior.STATE_HIDDEN) {
            dismiss()
        }

    }


    override fun onSlide(bottomSheet: View, slideOffset: Float) {
        if (slideOffset < -0.15f) {
            dismiss()
        }
    }
}


override fun setupDialog(dialog: Dialog, style: Int) {
    super.setupDialog(dialog, style)
    val view = View.inflate(context, R.layout.projects_edit_sheet, null)
    dialog.setContentView(view)

    dialog.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)


    val params = (view.parent as View).layoutParams as CoordinatorLayout.LayoutParams
    val behavior = params.behavior

    if (behavior != null && behavior is BottomSheetBehavior<*>) {
        behavior.setBottomSheetCallback(mBottomSheetBehaviorCallback)
    }


    // Get and set values
    val realm = Realm.getDefaultInstance()
    val realmObject = realm.where(ProjectsRealmObject::class.java)
            .equalTo("privateID", privateID)
            .findFirst()




    realm.beginTransaction()
    view.title_input.text = SpannableStringBuilder(realmObject.title)
    view.description_input.text = SpannableStringBuilder(realmObject.description)
    view.public_checkbox.isChecked = realmObject.isPublic
    realm.commitTransaction()


    // Keyboard
    view.title_input.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
        if (hasFocus) {
            (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(view.title_input, InputMethodManager.SHOW_FORCED)
        } else {
            (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(view.title_input.windowToken, 0)
        }
    }

    view.description_input.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
        if (hasFocus) {
            (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(view.description_input, InputMethodManager.SHOW_FORCED)
        } else {
            (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(view.description_input.windowToken, 0)
        }
    }


    // Click listners
    view.public_layout.setOnClickListener { view.public_checkbox.toggle() }

    view.cancel.setOnClickListener {
        view?.hideKeyboard()
        dismiss()
    }

    view.save.setOnClickListener {
        view?.hideKeyboard()
        // Save to realm
        realm.beginTransaction()
        realmObject.title = if (view.title_input.text.toString() == "") getString(R.string.unnamed) else view.title_input.text.toString()
        realmObject.description = view.description_input.text.toString()
        realmObject.isPublic = view.public_checkbox.isChecked
        realmObject.synced = false
        realmObject.updatedRealm = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()).toString() + ""
        realm.commitTransaction()

        ProjectsSync(context)

        toast("Sparat")

        dismiss()
    }

  }
}

XML:

<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
app:layout_collapseMode="none"
app:behavior_hideable="false"
app:behavior_peekHeight="100dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
style="@style/Widget.Design.BottomSheet.Modal">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/content">

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingRight="16dp"
            android:paddingLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="8dp">

            <android.support.design.widget.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/edit_info_placeholder_title"
                android:id="@+id/title_input"/>

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingRight="16dp"
            android:paddingLeft="16dp">

            <android.support.design.widget.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/edit_info_placeholder_description"
                android:id="@+id/description_input"/>

        </android.support.design.widget.TextInputLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:clickable="true"
            android:background="@drawable/click"
            android:paddingTop="8dp"
            android:paddingBottom="8dp"
            android:id="@+id/public_layout">

            <android.support.v7.widget.AppCompatCheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="12dp"
                android:id="@+id/public_checkbox"
                android:layout_marginRight="8dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/edit_info_placeholder_is_public"
                android:layout_gravity="center_vertical"
                style="@style/textMedium"/>

        </LinearLayout>


        <!-- Buttons -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="right"
            android:paddingBottom="8dp">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/edit_info_button_cancel"
                android:id="@+id/cancel"
                style="@style/Widget.AppCompat.Button.Borderless.Colored"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/edit_info_button_save"
                android:id="@+id/save"
                style="@style/Widget.AppCompat.Button.Borderless.Colored"/>

        </LinearLayout>

    </LinearLayout>


</FrameLayout>


Kotlin代码没问题,请发布您的styles.xml代码。 - 배준모
2
你使用的是哪个版本的Android设计库?在25.3.1中它可以正常工作,但在25.4.0中无法工作。 - orium
1
有关此事有任何更新吗? - orium
7个回答

118

我找到了27个API的解决方案。所以,即使使用SOFT_INPUT_ADJUST_RESIZE,键盘仍会隐藏视图的原因是对话框的windowIsFloating已设置。

我发现最方便的方法是创建样式来更改此设置:

<style name="DialogStyle" parent="Theme.Design.Light.BottomSheetDialog">
    <item name="android:windowIsFloating">false</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="android:windowSoftInputMode">adjustResize</item>
</style>

并将此设置在您的BottomSheetDialogFragmentonCreate方法中:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle)
}

这是在我的设备上的样子:

在此输入图片描述


10
不错的解决方案!另外要注意顶层布局必须是ScrollView,否则它不起作用。 - headsvk
2
@jblejder 或许您的布局足够简单,不需要它。我在编辑文本框下方有更多的 TextView 和按钮,因此我必须使用 ScrollView 包装 ConstraintLayout,否则它无法正常工作。 - headsvk
5
这个方案可行,我有一个复杂的父级ConstraintLayout,只有当我将该ConstraintLayout包裹在NestedScrollView中时才起作用(ScrollView无效)。 - Zayid Mohammed
@jblejder 我正在使用 Constraint Layout 并尝试您的解决方案,但它没有起作用,您可以同时添加您的 XML 代码吗? - Shruti
1
@CoolMind android:statusBarColor 不是必需的,但如果没有它,其他设置默认情况下会出现状态栏,这会破坏 BottomSheetDialog 的感觉。@Shruti 我刚刚再次尝试了我的解决方案,即使使用 ConstraintLayout 也似乎可以正常工作。只需确保您设置了所有垂直约束即可。 - jblejder
显示剩余8条评论

23

我尝试了此主题中的所有答案,但没有帮助。我查看了许多网站,只找到了一个适用于我的解决方案。

 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    val dialog = super.onCreateDialog(savedInstanceState)

    dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
    dialog.setOnShowListener {
        Handler().post {
            val bottomSheet = (dialog as? BottomSheetDialog)?.findViewById<View>(R.id.design_bottom_sheet) as? FrameLayout
            bottomSheet?.let {
                BottomSheetBehavior.from(it).state = BottomSheetBehavior.STATE_EXPANDED
            }
        }
    }

    return dialog
}

原始解决方案


4
我也尝试过,确实有效! - Neckster
1
也适用于我。 - Joseph Ofem

2
你可以使用下面的类:

最初的回答:

import android.graphics.Rect; 
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.BottomSheetDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

public class TestBottomSheetDialog extends BottomSheetDialogFragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View fragmentView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_bottom_sheet, container, false);
        if (getDialog().getWindow() != null) {
           getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        }
        if (getActivity() != null) {
            View decorView = getActivity().getWindow().getDecorView();
            decorView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
                Rect displayFrame = new Rect();
                decorView.getWindowVisibleDisplayFrame(displayFrame);
                int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
                int heightDifference = height - displayFrame.bottom;
                if (heightDifference != 0) {
                    if (fragmentView.getPaddingBottom() != heightDifference) {
                        fragmentView.setPadding(0, 0, 0, heightDifference);
                    }
                } else {
                    if (fragmentView.getPaddingBottom() != 0) {
                        fragmentView.setPadding(0, 0, 0, 0);
                    }
                }
            });
        }
        getDialog().setOnShowListener(dialog -> {
            BottomSheetDialog d = (BottomSheetDialog) dialog;
            View bottomSheetInternal = d.findViewById(android.support.design.R.id.design_bottom_sheet);
            if (bottomSheetInternal == null) return;
             BottomSheetBehavior.from(bottomSheetInternal).setState(BottomSheetBehavior.STATE_EXPANDED);
        });
        return fragmentView;
    }
}

1
你应该在回答中给出一些解释。 - Mikev

0

这对我有效

public class CustomBottomSheetDialogFragment extends BottomSheetDialogFragment 
{
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle 
    savedInstanceState) {
View v = inflater.inflate(R.layout.content_dialog_bottom_sheet, container, false);


getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    return v;
 }

可能是。我没有在27上测试过。如果您发现适用于安卓27的工作代码,请放上来。 - Irfan Raza

0

最高分数的答案部分正确。在我的情况下,设置相同的样式后,90%的视图是可见的。最终,我通过以下解决方案使其完全可见:

editText.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                (this@****BottomSheetDialogFragment.dialog as BottomSheetDialog).behavior.state = BottomSheetBehavior.STATE_EXPANDED
            }
        }

0

这个解决方案对我很有用,之前花了5个小时都没有成功:

步骤 #1:

将以下代码添加到styles.xml文件中(位于res\values文件夹中)

<style name="CustomizedBottomDialogStyle">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:backgroundDimEnabled">true</item>
    <item name="android:backgroundDimAmount">0.7</item>
    <item name="android:windowIsFloating">false</item>
    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="android:windowSoftInputMode">adjustResize</item>
    <item name="android:background">@android:color/transparent</item>
</style>

关键在于设置 android:windowIsFloating->false,如果设置为true,你的代码将无法运行!因此我使用了 android:backgroundDimEnabledandroid:backgroundDimAmount 来使背景具有美丽的叠加效果,看起来更透明。

第二步:

编写此函数以进行程序调整(请注意它不是可选项,您需要执行步骤#1和#2):

private fun showDialog() {

    BottomSheetDialog(requireActivity(), R.style.CustomizedBottomDialogStyle).apply {

        window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)

        setOnShowListener {
            Handler().post {
                val bottomSheet = findViewById<View>(R.id.design_bottom_sheet) as? FrameLayout
                bottomSheet?.let {
                    BottomSheetBehavior.from(it).state = STATE_EXPANDED
                }
            }
        }

        setContentView(R.layout.dialog_layout)

        // Your code goes here....

        show()
    }
}

-1
将此添加到您的样式中。
<style name="DialogStyle">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="colorPrimaryDark">@android:color/transparent</item>
</style>

然后在您的底部对话框的onCreate()中添加

setStyle(DialogFragment.STYLE_NO_FRAME, R.style.DialogStyle);

同时不要忘记将其添加到对话框的setupDialog()方法中

dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

现在它可以工作了。我已经单独发布了代码,对我来说是有效的。感谢您的建议,我也会尝试一下。 - Irfan Raza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接