web-dev-qa-db-ja.com

高さが固定されたBottomSheetDialogFragmentを実装するにはどうすればよいですか

BottomSheetDialogFragmentを実装して、問題に直面する必要があります。 BottomSheetDialogFragmentの高さが固定されている必要があります。誰かがそれを行う方法を知っていますか?

これが私のxmlのフラグメントコンテンツです

_<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent"
    Android:layout_height="@dimen/bottom_sheet_height"
    Android:background="@Android:color/white"
    Android:orientation="vertical">

    <TextView
        Android:id="@+id/drag_title"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:textSize="24sp"
        Android:textColor="#FF0000"
        Android:text="Title"/>

    <Android.support.v7.widget.RecyclerView
        Android:id="@+id/recycler_view"
        Android:layout_width="match_parent"
        Android:layout_height="0dp"
        Android:background="@Android:color/white"
        Android:layout_weight="1"/>

    <TextView
        Android:id="@+id/ok_button"
        Android:layout_width="match_parent"
        Android:layout_height="54dp"
        Android:background="@Android:color/holo_blue_dark"
        Android:gravity="center"
        Android:text="Hello"
        Android:textColor="@Android:color/white"
        Android:textSize="24sp"/>

</LinearLayout>
_

そしてsetupDialog()で私はこれをやっています:

_@Override
public void setupDialog(Dialog dialog, int style) {
    super.setupDialog(dialog, style);
    View contentView = View.inflate(getContext(), R.layout.bottom_sheet_dialog_content_view, null);
    dialog.setContentView(contentView);
    CoordinatorLayout.LayoutParams layoutParams = ((CoordinatorLayout.LayoutParams) ((View) contentView.getParent()).getLayoutParams());
    CoordinatorLayout.Behavior behavior = layoutParams.getBehavior();
    if (behavior != null && behavior instanceof BottomSheetBehavior) {
        ((BottomSheetBehavior) behavior).setBottomSheetCallback(bottomSheetCallback);
        ((BottomSheetBehavior) behavior).setPeekHeight(getResources().getDimensionPixelSize(R.dimen.bottom_sheet_height));
    }

    initRecyclerView(contentView);
}
_

そして、行動は非常に一般的です:

_private BottomSheetBehavior.BottomSheetCallback bottomSheetCallback = new BottomSheetBehavior.BottomSheetCallback() {
    @Override
    public void onStateChanged(@NonNull View bottomSheet, int newState) {
        if (newState == BottomSheetBehavior.STATE_HIDDEN) {
            dismiss();
        }
    }

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

PD:固定の高さをRecyclerViewに設定することで解決しました。誰かがより良いアプローチを知っていますか?

修正の高さは、スタイルを作成することで直接指定できます。

styles.xml

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

<style name="bottomSheetStyleWrapper" parent="Widget.Design.BottomSheet.Modal">
    <item name="behavior_peekHeight">500dp</item>
</style>

更新:

BottomSheetDialog dialog = new BottomSheetDialog(this, R.style.BottomSheetDialog);
dialog.setContentView(R.layout.layout_bottom_sheet);
dialog.show();

または2番目のアプローチ:

 CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) ((View) contentView.getParent()).getLayoutParams();
    CoordinatorLayout.Behavior behavior = params.getBehavior();

    if( behavior != null && behavior instanceof BottomSheetBehavior ) {
        ((BottomSheetBehavior) behavior).setBottomSheetCallback(mBottomSheetBehaviorCallback);
        ((BottomSheetBehavior) behavior).setPeekHeight(300);
    }
5

RecyclerViewコンテンツがinitRecyclerView(contentView);内に入力されている場合、BottomSheetを表示すると、その高さはよく知られています。 BottomSheetの高さを動的に設定し、コンテンツをラップするには、onResumeBottomSheetDialogFragment関数内にグローバルレイアウトリスナーを追加します。

@Override
public void onResume() {
    super.onResume();
    addGlobaLayoutListener(getView());
}

private void addGlobaLayoutListener(final View view) {
    view.addOnLayoutChangeListener(new OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            setPeekHeight(v.getMeasuredHeight());
            v.removeOnLayoutChangeListener(this);
        }
    });
}

public void setPeekHeight(int peekHeight) {
    BottomSheetBehavior behavior = getBottomSheetBehaviour();
    if (behavior == null) {
        return;
    }
    behavior.setPeekHeight(peekHeight);
}

private BottomSheetBehavior getBottomSheetBehaviour() {
    CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) ((View) getView().getParent()).getLayoutParams();
    CoordinatorLayout.Behavior behavior = layoutParams.getBehavior();
    if (behavior != null && behavior instanceof BottomSheetBehavior) {
        ((BottomSheetBehavior) behavior).setBottomSheetCallback(mBottomSheetBehaviorCallback);
        return (BottomSheetBehavior) behavior;
    }
    return null;
}
3
R. Zagórski

次のコードを試してください

enter image description here

  1. ボトムシートダイアログフラグメントのレイアウトxmlファイルを作成します

layout_bottom_sheet_dialog_fragment.xml

<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:Android="http://schemas.Android.com/apk/res/Android"
xmlns:tools="http://schemas.Android.com/tools"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
xmlns:app="http://schemas.Android.com/apk/res-auto">


<androidx.appcompat.widget.LinearLayoutCompat
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:orientation="vertical">

    <androidx.appcompat.widget.LinearLayoutCompat
        Android:id="@+id/ll_bottomSheetFrag_userProf"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:orientation="horizontal"
        Android:gravity="center"
        Android:padding="5dp">


        <de.hdodenhof.circleimageview.CircleImageView
            Android:layout_centerVertical="true"
            Android:layout_centerHorizontal="true"
            Android:src="@drawable/ic_profile_icon_nav_d"
            app:civ_border_width="1dp"
            app:civ_border_color="@color/main_white"
            Android:layout_height="70dp"
            Android:layout_width="70dp"
            Android:layout_marginLeft="5dp"
            Android:layout_marginRight="5dp"
            Android:contentDescription="@string/nav_header_desc"
            Android:paddingTop="@dimen/nav_header_vertical_spacing"
            Android:paddingBottom="@dimen/nav_header_vertical_spacing"
            Android:id="@+id/iv_bottomSheetFrag_userPic">
        </de.hdodenhof.circleimageview.CircleImageView>


        <!-- name & email -->
        <androidx.appcompat.widget.LinearLayoutCompat
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:orientation="vertical"
            Android:gravity="center"
            Android:layout_marginLeft="5dp"
            Android:layout_marginRight="5dp">

            <androidx.appcompat.widget.LinearLayoutCompat
                Android:layout_width="match_parent"
                Android:layout_height="wrap_content"
                Android:orientation="horizontal">

                <androidx.appcompat.widget.AppCompatTextView
                    Android:id="@+id/tv_bottomSheetFrag_userName"
                    Android:layout_width="match_parent"
                    Android:layout_height="wrap_content"
                    Android:paddingTop="5dp"
                    Android:paddingBottom="5dp"
                    Android:gravity="center|start"
                    Android:textSize="20sp"
                    Android:layout_weight="9"
                    Android:theme="@style/styleFontMediumText"
                    Android:text="@string/user_name"
                    Android:textAppearance="@style/TextAppearance.AppCompat.Body1"
                    Android:textColor="@color/black" />

                <androidx.appcompat.widget.AppCompatImageView
                    Android:id="@+id/iv_bottomSheetFrag_closeDialog"
                    Android:layout_width="wrap_content"
                    Android:layout_height="wrap_content"
                    Android:layout_weight="1"
                    Android:visibility="gone"
                    Android:contentDescription="@string/app_name"
                    Android:src="@drawable/ic_close_black_24dp"
                    />

            </androidx.appcompat.widget.LinearLayoutCompat>



            <androidx.appcompat.widget.AppCompatTextView
                Android:id="@+id/tv_bottomSheetFrag_userEmail"
                Android:layout_width="match_parent"
                Android:layout_height="wrap_content"
                Android:gravity="center|start"
                Android:textSize="14sp"
                Android:theme="@style/styleFontRegularText"
                Android:textColor="@color/primaryLightColor"
                Android:text="@string/user_email" />


        </androidx.appcompat.widget.LinearLayoutCompat>



    </androidx.appcompat.widget.LinearLayoutCompat>

    <View
        Android:layout_width="match_parent"
        Android:layout_height="0.5dp"
        Android:background="@color/divider_color"
        Android:layout_marginTop="5dp"
        Android:layout_marginBottom="5dp"/>

    <com.google.Android.material.navigation.NavigationView
        Android:id="@+id/nav_view_bottomSheetFrag"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        Android:layout_gravity="start"
        Android:fitsSystemWindows="true"
        app:elevation="0dp"
        app:itemTextAppearance="@style/NavDrawerTextStyle"
        app:itemBackground="@Android:color/transparent"
        app:itemIconTint="@color/nav_drawer_item_color_state"
        app:itemTextColor="@color/nav_drawer_item_color_state"
        app:menu="@menu/menu_bottom_sheet" />


</androidx.appcompat.widget.LinearLayoutCompat>
  1. BottomSheetDialogFragmentを拡張する必要があるボトムシートフラグメントのクラスを作成します

BottomSheetFragment.Java

public class BottomSheetFragment extends BottomSheetDialogFragment{
@BindView(R.id.iv_bottomSheetFrag_closeDialog) AppCompatImageView iv_closeDialog;
@BindView(R.id.nav_view_bottomSheetFrag_salesPerson) NavigationView nav_view;


private Context context;

//public constructor
public BottomSheetFragment() {

}

//create custom theme for your bottom sheet modal 
@Override
public int getTheme() {
    //return super.getTheme();
    return R.style.AppBottomSheetDialogTheme;
}


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    //return super.onCreateDialog(savedInstanceState);
    return new BottomSheetDialog(requireContext(), getTheme());  //set your created theme here

}


@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}


@Override
public void setupDialog(@NonNull Dialog dialog, int style)
{
    super.setupDialog(dialog, style);

    View contentView = View.inflate(getContext(), R.layout.layout_bottom_sheet_dialog_fragment, null);
    context = contentView.getContext();
    ButterKnife.bind(this, contentView);
    dialog.setContentView(contentView);
    //tv_title.setText(getString(R.string.app_name)); R.style.AppBottomSheetDialogTheme

    DisplayMetrics displayMetrics = getActivity().getResources().getDisplayMetrics();
    int width = displayMetrics.widthPixels;
    int height = displayMetrics.heightPixels;
    int maxHeight = (int) (height*0.44); //custom height of bottom sheet

    CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) ((View) contentView.getParent()).getLayoutParams();
    CoordinatorLayout.Behavior behavior = params.getBehavior();
    ((BottomSheetBehavior) behavior).setPeekHeight(maxHeight);  //changed default peek height of bottom sheet

    if (behavior != null && behavior instanceof BottomSheetBehavior)
    {
        ((BottomSheetBehavior) behavior).setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback()
        {

            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState)
            {
                String state = "";
                switch (newState)
                {
                    case BottomSheetBehavior.STATE_DRAGGING: {
                        //imgBtnClose.setVisibility(View.INVISIBLE);
                        iv_closeDialog.setVisibility(View.GONE);
                        state = "DRAGGING";
                        break;
                    }
                    case BottomSheetBehavior.STATE_SETTLING: {
                        // imgBtnClose.setVisibility(View.INVISIBLE);
                        iv_closeDialog.setVisibility(View.GONE);
                        state = "SETTLING";
                        break;
                    }
                    case BottomSheetBehavior.STATE_EXPANDED: {
                        // imgBtnClose.setVisibility(View.VISIBLE);
                        iv_closeDialog.setVisibility(View.VISIBLE);
                        state = "EXPANDED";
                        break;
                    }
                    case BottomSheetBehavior.STATE_COLLAPSED: {
                        //imgBtnClose.setVisibility(View.INVISIBLE);
                        iv_closeDialog.setVisibility(View.GONE);
                        state = "COLLAPSED";
                        break;
                    }
                    case BottomSheetBehavior.STATE_HIDDEN: {
                        // imgBtnClose.setVisibility(View.INVISIBLE);
                        iv_closeDialog.setVisibility(View.GONE);
                        dismiss();
                        state = "HIDDEN";
                        break;
                    }
                }
                Log.i("BottomSheetFrag", "onStateChanged: "+ state);
            }

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


    //close dialog
    iv_closeDialog.setOnClickListener(view -> dismiss());

}


@Override
public void onDestroyView() {
    super.onDestroyView();
}}
  1. これらの行をstyles.xmlに追加します。 styles.xml
<style name="AppBottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog">
        <item name="bottomSheetStyle">@style/AppModalStyle</item>
    </style>
    <style name="AppModalStyle" parent="Widget.Design.BottomSheet.Modal">
        <item name="Android:background">@drawable/rounded_dialog</item>
    </style>
  1. ボトムシート用の丸みを帯びた形状のドローアブル。このファイルをdrawablesフォルダーに追加します。

rounded_dialog.xml

 <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:shape="rectangle">
    <solid Android:color="@Android:color/white"/>
    <corners Android:topLeftRadius="16dp"
        Android:topRightRadius="16dp"/>

</shape>
  1. 最後に、アクティビティでこのダイアログフラグメントを次のように呼び出します。ここでは、bottomNavigationViewアイテムのonClickリスナーのフラグメントonClickを呼び出しました。
  private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = item ->


{
        Fragment selectedFragment = null;
        switch (item.getItemId()) {
            case R.id.bNav_menu:
                BottomSheetFragment bf = new BottomSheetFragment();
                bf.show(getSupportFragmentManager(), bf.getTag());
                //bf.setArguments(bundle);
                return true;
           
        }
    };
0
Rohan Shinde