步骤 1: 添加依赖
首先,确保你的 build.gradle
文件中包含了 Material Design
库的依赖。
dependencies {
//Material库
implementation("com.google.android.material:material:1.9.0") // 使用最新版本
}
步骤 2: 创建布局文件
在你的 res/layout
目录下创建一个布局文件,比如 fragment_bottom_dialog.xml
,定义底部对话框的布局。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:padding="10dp"
tools:context=".bottom.BottomDialogFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="这是一个底部滑出对话框" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="这是一个底部滑出对话框" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="这是一个底部滑出对话框" />
</LinearLayout>
步骤 3: 创建 BottomSheetDialogFragment 子类
创建一个继承自 BottomDialogFragment
的类,并重写 onCreateView
方法。
package edu.stu.myapplication.bottom
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import edu.stu.myapplication.R
class BottomDialogFragment : BottomSheetDialogFragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_bottom_dialog, container, false)
}
}
步骤 4: 显示 BottomSheetDialogFragment
在你的 Activity 或 Fragment 中,创建一个BottomDialogFragment
的实例。
package edu.stu.myapplication
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import edu.stu.myapplication.bottom.BottomDialogFragment
import edu.stu.myapplication.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val bottomDialogFragment = BottomDialogFragment()
binding.apply {
button.setOnClickListener {
bottomDialogFragment.show(supportFragmentManager, "test")
}
}
}
}
这样,你就完成了使用 BottomSheetDialogFragment
实现底部滑出对话框的基本步骤。你可以根据需求调整布局和功能。