[Android/Java] ModalBottomSheet

doooly·2023년 12월 16일
0

Android

목록 보기
3/5

Bottom Sheet 종류에는 2가지가 있습니다

  • Modal Bottom Sheet
  • Persistent Bottom Sheet

modal Bottom Sheet는 이벤트가 있을 때 아래에서 올라오는 Bottom Sheet이고,
Persistent Bottom Sheet는 기존부터 화면에 위치하는 Bottom Sheet로, 예시로는 네이버 지도의 하단 Sheet가 있습니다

이번 포스팅은 간단한 Modal Bottom Sheet를 만드는 법을 다루어 보도록 하겠습니다 ‼️



✅ xml 만들기

BottomSheet의 토대가 될 xml을 먼저 만들도록 하겠습니다

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <TextView
        android:id="@+id/bottom_sheet_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BottomSheet Example"
        android:padding="30dp"
        />
    <Button
        android:id="@+id/bottom_sheet_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="close"
        android:layout_marginStart="30dp"
        />
</LinearLayout>




✅ BottomSheet class 만들기

BottomSheetDialogFragment를 extend하는 custom class를 생성해줍니다

  • onCreateView()에서 위에서 만든 xml을 inflate해줍니다
public class BottomSheet extends BottomSheetDialogFragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.bottom_sheet, container, false);    }

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




✅ listener 만들기

만들어둔 btn에 click listener를 달아 누르면 sheet가 사라질 수 있도록 설정해줍니다


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button button = view.findViewById(R.id.bottom_sheet_btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }




✅ BottomSheet 호출

BottomSheet를 띄울 Fragment(혹은 Activity)의 버튼에 리스너를 달아줍니다
버튼을 클릭하면 만들었던 BottomSheet class를 생성해 화면에 띄웁니다

   Button btn = view.findViewById(R.id.bottom_sheet_btn);
   btn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           BottomSheet bottomSheet = new BottomSheet();
           bottomSheet.show(getActivity().getSupportFragmentManager(), null);
       }
  });





✅ 결과

의도한 대로 버튼을 누르면 BottomSheet가 생겨나며,
close 버튼을 누르면 sheet가 사라집니다

0개의 댓글