You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android中将PaymentActivity以Bottom Sheet Dialog形式打开

实现Activity以Bottom Sheet形式弹出的步骤

1. 定义弹出动画与主题样式

首先在res/anim目录下新增两个动画文件,控制底部弹出和退出的动效:
slide_in_bottom.xml(入场动画)

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromYDelta="100%"
    android:toYDelta="0%" />

slide_out_bottom.xml(退场动画)

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromYDelta="0%"
    android:toYDelta="100%" />

之后在res/values/styles.xml中新增Bottom Sheet风格的Activity主题:

<style name="Theme.BottomSheetActivity" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowAnimationStyle">@style/BottomSheetAnimation</item>
</style>

<style name="BottomSheetAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_in_bottom</item>
    <item name="android:windowExitAnimation">@anim/slide_out_bottom</item>
</style>

2. 给目标Activity绑定主题

打开AndroidManifest.xml,找到PaymentActivity的注册节点,添加主题配置:

<activity
    android:name=".PaymentActivity"
    android:theme="@style/Theme.BottomSheetActivity" />

3. 调整PaymentActivity窗口参数

在PaymentActivity的onCreate生命周期中配置窗口对齐规则、宽高和交互逻辑:

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

    window?.let { win ->
        val layoutParams = win.attributes
        // 窗口底部对齐
        layoutParams.gravity = Gravity.BOTTOM
        // 宽度占满屏幕
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT
        // 高度可根据需求调整,WRAP_CONTENT为自适应内容,也可写固定dp值
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
        win.attributes = layoutParams
        // 点击窗口外部自动关闭,不需要可设为false
        setFinishOnTouchOutside(true)
    }

    // 接收传递的参数
    val totalAmount = intent.getStringExtra("total_amount")
    // 后续业务逻辑
}

4. 原有跳转逻辑无需修改

你原本的跳转代码可以直接保留,正常调用就能弹出底部样式的Activity:

if (success) {
    val intent = Intent(this, PaymentActivity::class.java)
    intent.putExtra("total_amount",totalAmount)
    startActivity(intent)
    // 如果不需要关闭当前栈内所有Activity,可删除这行
    finishAffinity()
}

注意事项

  • 如果需要限制Activity的最大高度,可把layoutParams.height改成(resources.displayMetrics.heightPixels * 0.75).toInt(),即可限制最高占屏幕的75%
  • 如果不需要滑动关闭效果,也可替换实现方案为BottomSheetDialogFragment,交互适配性更优

内容的提问来源于stack exchange,提问作者yazhini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 10:54:04