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

如何在Android中实现Fold4布局:普通机全屏/折叠机留空白

折叠屏适配:普通手机全屏、折叠屏留空白的实现方案

以下几种方法可以实现你的需求:

方法一:使用资源限定符(静态适配)

通过Android的资源限定符,为不同屏幕尺寸的设备提供不同布局:

  • 在res/layout/目录下的布局文件(适配普通手机):
    <View
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ... />
    
  • 在res/layout-sw720dp/目录下创建同名布局文件(适配折叠屏展开后的大屏):
    <View
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxWidth="600dp"
        android:layout_gravity="center_horizontal"
        ... />
    
    注:sw720dp表示设备最小宽度为720dp,可根据折叠屏实际尺寸调整阈值;maxWidth限制内容最大宽度,确保两边留空白。

方法二:动态判断屏幕尺寸(代码适配)

在代码中获取屏幕宽度,根据阈值调整布局宽度:

val targetView = findViewById<View>(R.id.your_target_view)
val screenWidth = resources.displayMetrics.widthPixels
// 设定折叠屏展开的宽度阈值(比如720dp对应的像素值)
val foldThreshold = (720 * resources.displayMetrics.density).toInt()

if (screenWidth > foldThreshold) {
    // 折叠屏展开状态:设置固定宽度并居中
    targetView.layoutParams.width = (600 * resources.displayMetrics.density).toInt()
    (targetView.layoutParams as ViewGroup.MarginLayoutParams).gravity = Gravity.CENTER_HORIZONTAL
} else {
    // 普通手机:全屏显示
    targetView.layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
}
targetView.requestLayout()

方法三:使用Jetpack WindowManager(官方推荐)

通过官方库准确判断折叠屏状态,实现精准适配:

  1. 首先添加依赖:
    implementation "androidx.window:window:1.1.0"
    
  2. 监听窗口布局状态并调整:
    import androidx.window.layout.WindowInfoRepository
    import androidx.window.layout.WindowInfoRepository.Companion.getOrCreate
    import androidx.window.layout.FoldingFeature
    import kotlinx.coroutines.launch
    import androidx.lifecycle.lifecycleScope
    
    lifecycleScope.launch {
        val windowInfoRepo = getOrCreate(this@YourActivity)
        windowInfoRepo.windowLayoutInfo.collect { layoutInfo ->
            val isFoldExpanded = layoutInfo.displayFeatures.any {
                it is FoldingFeature && it.state == FoldingFeature.State.FLAT
            }
            val targetView = findViewById<View>(R.id.your_target_view)
    
            if (isFoldExpanded) {
                targetView.layoutParams.width = (600 * resources.displayMetrics.density).toInt()
                (targetView.layoutParams as ViewGroup.MarginLayoutParams).gravity = Gravity.CENTER_HORIZONTAL
            } else {
                targetView.layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
            }
            targetView.requestLayout()
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:53:10