简体   繁体   English

根据 Android Compose 中的可用宽度/高度显示不同的内容(布局)

[英]Show different content (layouts) depending on available width/height in Android Compose

I have an Activity and MyApp composable function.我有一个ActivityMyApp可组合功能。 In the function I need to show either list with details or just list screen depending on the available width.在函数中,我需要根据可用宽度显示包含详细信息的列表或仅显示列表屏幕。 How to determine available width for the content I want to show using Jetpack Compose ?如何确定我想使用Jetpack Compose显示的内容的可用宽度? What is a good practice for this using Compose ?使用Compose有什么好的做法?

class MyActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ProjectTheme {
                MyApp()
            }
        }
    }
}

@Composable
fun MyApp() {
    val isLarge: Boolean = ...// how to determine whether the available width is large enough?
    if (isLarge) {
        ListScreenWithDetails()
    } else {
        ListScreen()
    }
}

@Composable
fun ProjectTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
    // ... project theme
}

You can use :您可以使用 :

val configuration = LocalConfiguration.current

Then:然后:

val isLargeWidth = configuration.screenWidthDp > 840

For a generic solution, consider using the Window Size Classes, see this and this for reference.对于通用解决方案,请考虑使用 Window Size Classes,请参阅thisthis以供参考。

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContent {
        val windowSizeClass = calculateWindowSizeClass(this)
        MyApp(windowSizeClass)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM