Keyboard hides BottomSheetDialogFragment

后端 未结 6 1418
走了就别回头了
走了就别回头了 2020-12-04 13:22

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. How do I fix this issue

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 14:10

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

提交回复
热议问题