简体   繁体   English

键盘隐藏BottomSheetDialogFragment

[英]Keyboard hides BottomSheetDialogFragment

There are more fields below the keyboard.键盘下方有更多字段。 This happened when i updated the support library.这发生在我更新支持库时。 I know it's Kotlin but it looks almost the same as java.我知道它是 Kotlin,但它看起来和 java 几乎一样。 How do I fix this issue?我该如何解决这个问题?

This is what it looks like:这是它的样子:

在此处输入图片说明

My code:我的代码:

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: 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>

I found the solution for 27 api.我找到了 27 api 的解决方案。 So the reason why keyboard hides view even with SOFT_INPUT_ADJUST_RESIZE is that the windowIsFloating is set for Dialogs.所以即使使用 SOFT_INPUT_ADJUST_RESIZE 键盘也隐藏视图的原因是 windowIsFloating 是为 Dialogs 设置的。

The most convenient way that I found to change this is by creating style:我发现改变这种情况的最方便的方法是创建样式:

<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>

And set this in onCreate method of your BottomSheetDialogFragment :并在您的BottomSheetDialogFragment onCreate方法中设置它:

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

This is how it looks on my device:这是它在我的设备上的外观:

在此处输入图片说明

I tried all of answers in this topic but nothing helped.我尝试了本主题中的所有答案,但没有任何帮助。 I looked through many sites and found only one solution that working for me.我浏览了许多网站,只找到了一种适合我的解决方案。

 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
}

Original solution 原解决方案

You can use the next class:您可以使用下一个类:

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;
    }
}

This is working for me这对我有用

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;
 }

This solution worked for me after spending 5 hours without luck:这个解决方案在没有运气的情况下花了 5 个小时后对我有用:

Step #1:第1步:

Add this code to your styles.xml (located in res\\values folder)将此代码添加到您的 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>

The key here is to set android:windowIsFloating -> false , if it is true your code will not work!这里的关键是设置android:windowIsFloating -> false ,如果它是真的你的代码将无法工作! Therefor i used rather android:backgroundDimEnabled and android:backgroundDimAmount to make background looks transparent with beautiful overlay.因此,我使用了android:backgroundDimEnabledandroid:backgroundDimAmount来使背景看起来透明并带有漂亮的叠加层。

Step #2:第2步:

Write this function to adjust it programmatically (note it is not optional, you need to perform both steps #1 and #2):编写此函数以编程方式调整它(注意它不是可选的,您需要同时执行步骤 #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()
    }
}

add this to your styles将此添加到您的样式中

<style name="DialogStyle">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="colorPrimaryDark">@android:color/transparent</item>
</style>

then in your's bottom sheet dialog's onCreate() add然后在您的底部工作表对话框的 onCreate() 添加

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

also don't forget to add to dialog's setupDialog() method也不要忘记添加到对话框的 setupDialog() 方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM