显示不同的内容(布局)取决于可用的宽度/高度在Android撰写



我有一个ActivityMyApp可组合函数。在函数中,我需要显示列表的详细信息或只是列表屏幕取决于可用的宽度。如何确定我想使用Jetpack 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
}

您可以使用:

val configuration = LocalConfiguration.current

:

val isLargeWidth = configuration.screenWidthDp > 840

对于一个通用的解决方案,考虑使用窗口大小类,参考这个和这个。

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val windowSizeClass = calculateWindowSizeClass(this)
MyApp(windowSizeClass)
}
}

最新更新