最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android?BottomSheetBehavior使用方法及常見問題詳解

 更新時(shí)間:2025年12月26日 08:55:35   作者:モンキー?D?小菜雞兒  
這篇文章主要介紹了Android?BottomSheetBehavior使用方法及常見問題的相關(guān)資料,BottomSheetBehavior是AndroidX中用于實(shí)現(xiàn)底部彈出式面板(底部抽屜)的行為類,支持拖拽、展開/收起、狀態(tài)監(jiān)聽等核心能力,需要的朋友可以參考下

前言

BottomSheetBehavior 是 Android Support Library(現(xiàn) AndroidX)中 com.google.android.material.bottomsheet.BottomSheetBehavior 提供的一個(gè)行為類,用于實(shí)現(xiàn)底部彈出式面板(底部抽屜)效果,支持拖拽、展開/收起、狀態(tài)監(jiān)聽等核心能力,廣泛應(yīng)用于底部菜單、篩選面板、詳情彈窗等場(chǎng)景。

一、基礎(chǔ)準(zhǔn)備

1. 依賴引入

確保項(xiàng)目中引入 Material Design 依賴(AndroidX 版本):

dependencies {
    // 核心 Material Design 庫(kù)(包含 BottomSheetBehavior)
    implementation 'com.google.android.material:material:1.12.0'
    // 基礎(chǔ) AppCompat 庫(kù)(可選,根據(jù)項(xiàng)目需求)
    implementation 'androidx.appcompat:appcompat:1.7.0'
}

2. 布局基礎(chǔ)結(jié)構(gòu)

BottomSheetBehavior 需作用于 CoordinatorLayout 的子 View,核心布局結(jié)構(gòu)如下:

<?xml version="1.0" encoding="utf-8"?>
<!-- 必須使用 CoordinatorLayout 作為父布局 -->
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 主內(nèi)容區(qū)域(如 RecyclerView、LinearLayout 等) -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp">

        <Button
            android:id="@+id/btnShowBottomSheet"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="顯示底部面板"/>

    </LinearLayout>

    <!-- 底部面板(BottomSheet) -->
    <LinearLayout
        android:id="@+id/bottomSheet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@android:color/white"
        android:padding="16dp"
        <!-- 核心屬性:綁定 BottomSheetBehavior -->
        app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="底部面板標(biāo)題"
            android:textSize="18sp"
            android:textStyle="bold"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="底部面板內(nèi)容區(qū)域,支持拖拽展開/收起"
            android:marginTop="8dp"/>

        <Button
            android:id="@+id/btnClose"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="關(guān)閉面板"
            android:marginTop="16dp"/>

    </LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

二、核心 API 與基礎(chǔ)使用

1. 獲取 BottomSheetBehavior 實(shí)例

在 Activity/Fragment 中獲取 Behavior 實(shí)例,用于控制底部面板:

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.bottomsheet.BottomSheetBehavior
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    // 聲明 BottomSheetBehavior 實(shí)例
    private lateinit var bottomSheetBehavior: BottomSheetBehavior<*>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 初始化 BottomSheetBehavior
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet)

        // 初始化點(diǎn)擊事件
        initClickEvents()
        // 初始化 Behavior 配置
        initBottomSheetConfig()
    }

    private fun initClickEvents() {
        // 顯示底部面板
        btnShowBottomSheet.setOnClickListener {
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
        }

        // 關(guān)閉底部面板
        btnClose.setOnClickListener {
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
        }
    }
}

2. 核心狀態(tài)常量

BottomSheetBehavior 提供了多種狀態(tài)控制面板行為,常用狀態(tài)如下:

狀態(tài)常量說明
STATE_COLLAPSED折疊狀態(tài)(默認(rèn)高度,可通過 peekHeight 設(shè)置)
STATE_EXPANDED完全展開狀態(tài)(占滿屏幕高度)
STATE_HIDDEN隱藏狀態(tài)(需先設(shè)置 behavior.setHideable(true)
STATE_HALF_EXPANDED半展開狀態(tài)(Android 11+ 支持,需設(shè)置 fitToContents = false
STATE_DRAGGING拖拽中狀態(tài)(不可手動(dòng)設(shè)置,僅監(jiān)聽)
STATE_SETTLING滑動(dòng)中狀態(tài)(不可手動(dòng)設(shè)置,僅監(jiān)聽)

3. 關(guān)鍵配置項(xiàng)

(1)設(shè)置折疊高度(peekHeight)

控制面板折疊時(shí)顯示的高度,默認(rèn)值為 56dp:

private fun initBottomSheetConfig() {
    // 設(shè)置折疊高度(單位:px)
    bottomSheetBehavior.peekHeight = 200 // 也可使用 dp2px 工具類轉(zhuǎn)換

    // 允許隱藏面板(設(shè)置后才能使用 STATE_HIDDEN 狀態(tài))
    bottomSheetBehavior.isHideable = true

    // 是否適配內(nèi)容高度(false 時(shí)支持半展開狀態(tài))
    bottomSheetBehavior.isFitToContents = false

    // 設(shè)置最大展開高度(Android 11+ 支持)
    bottomSheetBehavior.maxWidth = resources.displayMetrics.widthPixels
    bottomSheetBehavior.maxHeight = resources.displayMetrics.heightPixels / 2
}

// 工具類:dp 轉(zhuǎn) px
private fun dp2px(dp: Int): Int {
    val density = resources.displayMetrics.density
    return (dp * density + 0.5f).toInt()
}

(2)設(shè)置拖拽禁用

禁止用戶手動(dòng)拖拽面板,僅通過代碼控制狀態(tài):

bottomSheetBehavior.isDraggable = false

三、狀態(tài)監(jiān)聽

通過 BottomSheetCallback 監(jiān)聽面板狀態(tài)變化,實(shí)現(xiàn)業(yè)務(wù)邏輯聯(lián)動(dòng):

private fun initBottomSheetListener() {
    bottomSheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
        // 面板滑動(dòng)時(shí)回調(diào)(dy:垂直滑動(dòng)距離)
        override fun onSlide(bottomSheet: View, slideOffset: Float) {
            // slideOffset:滑動(dòng)偏移量(0:折疊狀態(tài),1:完全展開,-1:隱藏)
            Log.d("BottomSheet", "滑動(dòng)偏移量:$slideOffset")
            // 示例:根據(jù)偏移量改變面板透明度
            bottomSheet.alpha = 0.8f + slideOffset * 0.2f
        }

        // 面板狀態(tài)變化時(shí)回調(diào)
        override fun onStateChanged(bottomSheet: View, newState: Int) {
            when (newState) {
                BottomSheetBehavior.STATE_EXPANDED -> {
                    Log.d("BottomSheet", "完全展開")
                    // 展開時(shí)的業(yè)務(wù)邏輯:如隱藏軟鍵盤、更新UI等
                }
                BottomSheetBehavior.STATE_COLLAPSED -> {
                    Log.d("BottomSheet", "折疊")
                }
                BottomSheetBehavior.STATE_HIDDEN -> {
                    Log.d("BottomSheet", "隱藏")
                }
                BottomSheetBehavior.STATE_HALF_EXPANDED -> {
                    Log.d("BottomSheet", "半展開")
                }
                BottomSheetBehavior.STATE_DRAGGING -> {
                    Log.d("BottomSheet", "拖拽中")
                }
                BottomSheetBehavior.STATE_SETTLING -> {
                    Log.d("BottomSheet", "滑動(dòng)中")
                }
            }
        }
    })
}

四、高級(jí)用法

1. 全屏底部面板(無折疊高度)

實(shí)現(xiàn)點(diǎn)擊按鈕彈出全屏底部面板,且禁止折疊:

// 初始化配置
bottomSheetBehavior.peekHeight = 0 // 折疊高度設(shè)為0
bottomSheetBehavior.isHideable = true
bottomSheetBehavior.isDraggable = true

// 顯示全屏面板
btnShowFullScreenSheet.setOnClickListener {
    bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
}

2. 嵌套滾動(dòng)處理

若底部面板包含 RecyclerView/NestedScrollView,需處理嵌套滾動(dòng)沖突:

<!-- 底部面板內(nèi)的 RecyclerView 配置 -->
<androidx.recyclerview.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

同時(shí)在代碼中啟用嵌套滾動(dòng):

recyclerView.isNestedScrollingEnabled = true

3. 自定義底部面板樣式

通過設(shè)置背景、圓角、陰影美化面板:

<!-- 底部面板根布局 -->
<LinearLayout
    android:id="@+id/bottomSheet"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_bottom_sheet"
    android:elevation="8dp"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

    <!-- 內(nèi)容 -->
</LinearLayout>

bg_bottom_sheet.xml(drawable 資源):

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/white"/>
    <corners
        android:topLeftRadius="16dp"
        android:topRightRadius="16dp"/>
    <padding android:all="16dp"/>
</shape>

五、常見問題與解決方案

1. 面板無法隱藏

  • 原因:未設(shè)置 isHideable = true;
  • 解決方案:調(diào)用 bottomSheetBehavior.isHideable = true 后再設(shè)置 STATE_HIDDEN 狀態(tài)。

2. 半展開狀態(tài)不生效

  • 原因:Android 11 以下不支持,或未設(shè)置 isFitToContents = false
  • 解決方案:
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        bottomSheetBehavior.isFitToContents = false
        bottomSheetBehavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED
    }
    

3. 拖拽時(shí)與其他 View 沖突

  • 原因:嵌套滾動(dòng)未處理,或多個(gè) Behavior 沖突;
  • 解決方案:
    1. 禁用非目標(biāo) View 的拖拽:bottomSheetBehavior.isDraggable = false;
    2. 為嵌套滾動(dòng) View 設(shè)置 app:layout_behavior="@string/appbar_scrolling_view_behavior";
    3. 重寫 onInterceptTouchEvent 處理觸摸事件。

4. 面板高度超出屏幕

  • 原因:面板內(nèi)容高度過高,未設(shè)置 wrap_content;
  • 解決方案:
    1. 面板根布局高度設(shè)為 wrap_content;
    2. 內(nèi)部使用滾動(dòng)布局(如 NestedScrollView)包裹內(nèi)容。

六、完整示例代碼

布局文件(activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp"
        android:gravity="center">

        <Button
            android:id="@+id/btnExpand"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="展開面板"/>

        <Button
            android:id="@+id/btnCollapse"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="折疊面板"
            android:marginTop="8dp"/>

        <Button
            android:id="@+id/btnHide"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="隱藏面板"
            android:marginTop="8dp"/>

    </LinearLayout>

    <!-- 底部面板 -->
    <LinearLayout
        android:id="@+id/bottomSheet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_bottom_sheet"
        android:elevation="8dp"
        android:orientation="vertical"
        android:padding="16dp"
        app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="底部面板"
            android:textSize="20sp"
            android:textStyle="bold"/>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:marginTop="16dp"/>

        <Button
            android:id="@+id/btnClose"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="關(guān)閉"
            android:marginTop="16dp"/>

    </LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Kotlin 代碼(MainActivity.kt)

import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.bottomsheet.BottomSheetBehavior
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private lateinit var bottomSheetBehavior: BottomSheetBehavior<*>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 初始化 BottomSheetBehavior
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet)

        // 初始化配置
        initConfig()

        // 初始化監(jiān)聽
        initListener()

        // 初始化點(diǎn)擊事件
        initClick()

        // 初始化 RecyclerView(示例)
        initRecyclerView()
    }

    private fun initConfig() {
        // 設(shè)置折疊高度
        bottomSheetBehavior.peekHeight = dp2px(100)
        // 允許隱藏
        bottomSheetBehavior.isHideable = true
        // 支持半展開(Android 11+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            bottomSheetBehavior.isFitToContents = false
        }
        // 禁用拖拽(可選)
        // bottomSheetBehavior.isDraggable = false
    }

    private fun initListener() {
        bottomSheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
            override fun onSlide(bottomSheet: View, slideOffset: Float) {
                Log.d("BottomSheet", "滑動(dòng)偏移量:$slideOffset")
            }

            override fun onStateChanged(bottomSheet: View, newState: Int) {
                when (newState) {
                    BottomSheetBehavior.STATE_EXPANDED -> Log.d("BottomSheet", "完全展開")
                    BottomSheetBehavior.STATE_COLLAPSED -> Log.d("BottomSheet", "折疊")
                    BottomSheetBehavior.STATE_HIDDEN -> Log.d("BottomSheet", "隱藏")
                    BottomSheetBehavior.STATE_HALF_EXPANDED -> Log.d("BottomSheet", "半展開")
                    else -> Log.d("BottomSheet", "其他狀態(tài):$newState")
                }
            }
        })
    }

    private fun initClick() {
        btnExpand.setOnClickListener {
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
        }

        btnCollapse.setOnClickListener {
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
        }

        btnHide.setOnClickListener {
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN
        }

        btnClose.setOnClickListener {
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
        }
    }

    private fun initRecyclerView() {
        // 示例:為 RecyclerView 設(shè)置簡(jiǎn)單適配器
        recyclerView.adapter = SimpleAdapter(getData())
        recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
    }

    // 模擬數(shù)據(jù)
    private fun getData(): List<String> {
        val list = mutableListOf<String>()
        for (i in 1..20) {
            list.add("列表項(xiàng) $i")
        }
        return list
    }

    // dp 轉(zhuǎn) px
    private fun dp2px(dp: Int): Int {
        val density = resources.displayMetrics.density
        return (dp * density + 0.5f).toInt()
    }

    // 簡(jiǎn)單適配器
    inner class SimpleAdapter(private val data: List<String>) :
        androidx.recyclerview.widget.RecyclerView.Adapter<SimpleAdapter.ViewHolder>() {

        inner class ViewHolder(itemView: View) :
            androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
            val tv: TextView = itemView as TextView
        }

        override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): ViewHolder {
            val tv = TextView(parent.context)
            tv.layoutParams = androidx.recyclerview.widget.RecyclerView.LayoutParams(
                androidx.recyclerview.widget.RecyclerView.LayoutParams.MATCH_PARENT,
                dp2px(40)
            )
            tv.padding = dp2px(8)
            return ViewHolder(tv)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.tv.text = data[position]
        }

        override fun getItemCount(): Int = data.size
    }
}

七、總結(jié)

BottomSheetBehavior 是實(shí)現(xiàn)底部面板的核心組件,核心要點(diǎn):

  1. 必須依賴 Material Design 庫(kù),且父布局為 CoordinatorLayout;
  2. 通過 from() 方法獲取 Behavior 實(shí)例,控制面板狀態(tài);
  3. 常用狀態(tài):STATE_EXPANDED(展開)、STATE_COLLAPSED(折疊)、STATE_HIDDEN(隱藏);
  4. 可通過 peekHeight、isHideable、isFitToContents 等配置自定義行為;
  5. 利用 BottomSheetCallback 監(jiān)聽狀態(tài)變化,實(shí)現(xiàn)業(yè)務(wù)聯(lián)動(dòng)。

適用于底部菜單、篩選面板、詳情彈窗、地圖底欄等場(chǎng)景,是 Android 開發(fā)中高頻使用的組件。

到此這篇關(guān)于Android BottomSheetBehavior使用方法及常見問題的文章就介紹到這了,更多相關(guān)Android BottomSheetBehavior使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

绥化市| 循化| 汉阴县| 成安县| 高碑店市| 新蔡县| 武邑县| 阜阳市| 威信县| 梅州市| 区。| 尉氏县| 墨竹工卡县| 尼玛县| 张家界市| 伊春市| 罗源县| 防城港市| 洛南县| 东丽区| 东乡县| 高雄市| 诸暨市| 博爱县| 南充市| 玉溪市| 乡城县| 延长县| 扎兰屯市| 河曲县| 陇西县| 丰原市| 志丹县| 双峰县| 泰兴市| 台北市| 揭阳市| 桐城市| 瑞丽市| 泰安市| 改则县|