The Cook
The Cook

Reputation: 1443

How to scroll up in GridView that is in a BottomSheetDialog?

I created a BottomSheetDialog that has a GridView in it. When the BottomSheetDialog is opened, you can scroll down normally. Doing so makes the BottomSheetDialog expand to full screen and scroll down in GridView normally.

However when user tries to scroll up; instead of scrolling up in GridView, BottomSheetDialog shrinks and closes.

What I want is being able to scroll up and down in GridView without BottomSheetDialog changing sizes.

How to do it?

My Code:

final BottomSheetDialog dialog = new BottomSheetDialog(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.grid, null);
dialog.setContentView(view);

grid.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <GridView
        android:background="#FFFFFF"
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:stretchMode="columnWidth"
        android:horizontalSpacing="4dp"
        android:verticalSpacing="4dp"
        android:gravity="center"
        />

</LinearLayout>

Upvotes: 3

Views: 1834

Answers (1)

The Cook
The Cook

Reputation: 1443

Solved:

dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(final DialogInterface dialog) {
                    BottomSheetDialog d = (BottomSheetDialog) dialog;
                    FrameLayout bottomSheet = (FrameLayout) d.findViewById(android.support.design.R.id.design_bottom_sheet);
                    // Right here!
                    final BottomSheetBehavior behaviour = BottomSheetBehavior.from(bottomSheet);
                    behaviour.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                        @Override
                        public void onStateChanged(@NonNull View bottomSheet, int newState) {
                            if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                                dialog.dismiss();
                            }

                            if (newState == BottomSheetBehavior.STATE_DRAGGING) {
                                ((BottomSheetBehavior) behaviour).setState(BottomSheetBehavior.STATE_EXPANDED);
                            }
                        }

                        @Override
                        public void onSlide(@NonNull View bottomSheet, float slideOffset) {

                        }
                    });
                }
            });

Upvotes: 5

Related Questions