Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีใช้ BottomSheet ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตการใช้ BottomSheetBehavior จาก Material Design Support Library เพื่อสร้างแผ่นเลื่อนจากด้านล่าง

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio → File → New Project และกรอกข้อมูลที่จำเป็น

ขั้นตอนที่ 2: เพิ่ม Dependencies (build.gradle Module:app)

dependencies {
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    
    // สำหรับ AndroidX (แนะนำปัจจุบัน)
    // implementation 'com.google.android.material:material:1.11.0'
    // implementation 'com.jakewharton:butterknife:10.2.3'
    // annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3'
}

ขั้นตอนที่ 3: เลย์เอาต์หลัก (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/Widget.Support.CoordinatorLayout" />
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content" />

    <!-- Bottom Sheet วางหลัง Content -->
    <include layout="@layout/bottomsheet" />

</android.support.design.widget.CoordinatorLayout>

ขั้นตอนที่ 4: Bottom Sheet Layout (res/layout/bottomsheet.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:id="@+id/bottomSheet"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp"
    app:behavior_hideable="true"
    app:behavior_peekHeight="100dp"
    app:layout_behavior="android.support.design.widget.BottomSheetBehavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="3">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="Order Details"
            android:textColor="#444"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="end"
            android:text="₹435.00"
            android:textSize="15sp"
            android:textStyle="bold" />

    </LinearLayout>

    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Chicken BBQ" />
    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Chicken Biriyani" />
    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Delivery Address" android:textColor="#444" android:textStyle="bold" />
    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Flat No 404, India, Chennai" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:background="#000"
        android:text="PROCEED PAYMENT"
        android:textColor="#fff" />

</LinearLayout>

ขั้นตอนที่ 5: Content Layout (res/layout/content.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="MainActivity"
    tools:showIn="@layout/activity_main">

    <Button
        android:id="@+id/btnBottomSheet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Bottom Sheet"
        android:layout_centerInParent="true" />

</RelativeLayout>

ขั้นตอนที่ 6: โค้ดหลัก (src/MainActivity.java)

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {
    @BindView(R.id.btnBottomSheet) Button btnBottomSheet;
    @BindView(R.id.bottomSheet) LinearLayout layoutBottomSheet;
    
    BottomSheetBehavior<LinearLayout> sheetBehavior;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        Toolbar toolbar = findViewById(R.id.toolbar);
        // setSupportActionBar(toolbar);

        // เริ่มต้น BottomSheetBehavior
        sheetBehavior = BottomSheetBehavior.from(layoutBottomSheet);
        
        // ตั้งค่า Callback
        sheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                switch (newState) {
                    case BottomSheetBehavior.STATE_HIDDEN:
                        break;
                    case BottomSheetBehavior.STATE_EXPANDED:
                        btnBottomSheet.setText("Close Sheet");
                        break;
                    case BottomSheetBehavior.STATE_COLLAPSED:
                        btnBottomSheet.setText("Expand Sheet");
                        break;
                    case BottomSheetBehavior.STATE_DRAGGING:
                    case BottomSheetBehavior.STATE_SETTLING:
                        break;
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                // slideOffset: 0.0 (Collapsed) ถึง 1.0 (Expanded)
            }
        });
    }

    @OnClick(R.id.btnBottomSheet)
    public void toggleBottomSheet() {
        if (sheetBehavior.getState() != BottomSheetBehavior.STATE_EXPANDED) {
            sheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            btnBottomSheet.setText("Close sheet");
        } else {
            sheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            btnBottomSheet.setText("Expand sheet");
        }
    }
}

ขั้นตอนที่ 7: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

การทดสอบ

รันแอป กดปุ่ม "Show Bottom Sheet" จะเลื่อนขึ้นมา กดอีกครั้งหรือลากลงเพื่อปิด

วิธีใช้ BottomSheet ใน Android วิธีใช้ BottomSheet ใน Android

สถานะของ BottomSheetBehavior

Stateคำอธิบาย
STATE_COLLAPSEDยุบอยู่ แสดงแค่ peekHeight
STATE_EXPANDEDขยายเต็มที่
STATE_DRAGGINGผู้ใช้กำลังลาก
STATE_SETTLINGกำลังแอนิเมชันไปสู่ State ใหม่
STATE_HIDDENซ่อนหาย (ต้องตั้ง behavior_hideable=true)
STATE_HALF_EXPANDEDขยายครึ่งหนึ่ง (Material 1.2+)

อัปเดตสำหรับ AndroidX (ปัจจุบัน)

// build.gradle (AndroidX)
implementation 'com.google.android.material:material:1.11.0'

// Import
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

// ใช้ BottomSheetDialogFragment แทน (ง่ายกว่า)
public class MyBottomSheetDialog extends BottomSheetDialogFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.bottom_sheet_layout, container, false);
    }
}

// แสดง
new MyBottomSheetDialog().show(getSupportFragmentManager(), "TAG");
📝 หมายเหตุ: ตัวอย่างใช้ Support Library (เก่า) ปัจจุบันควรย้ายไป AndroidX และ Material Components Library