Android中使用kotlin实现实现底部滑出对话框的组件BottomSheetDialogFragment

步骤 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 实现底部滑出对话框的基本步骤。你可以根据需求调整布局和功能。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值