此代码片段进行无限重组 滚动时,找不到原因?
如何在 Jetpack Compose 中管理 HorizontalPager 中的状态和动画?
我正在使用 Jetpack Compose 并尝试创建一个涉及 HorizontalPager 的自定义对话框 UI。我在 MainActivity 中使用 ComposeView 来显示此 UI,但在管理状态、动画和初始页面设置时遇到了问题。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val compose = findViewById<ComposeView>(R.id.composeErrorScreen)
compose.apply {
visibility = VISIBLE
setContent {
val dialogContentState by remember {
mutableStateOf(
CardsScreenUi(
2, // initialCard
listOf(2, 3, 4) // cardsList
)
)
}
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Transparent),
contentAlignment = Alignment.BottomEnd
) {
DialogContent(dialogContentState)
}
}
}
}
}
这里我通过 JetPack Compose 添加一个可组合项
internal data class CardsScreenUi(
val initialCard: Int,
val cardsList: List<Int>
)
@Composable
internal fun BoxScope.DialogContent(
dialogContentState: CardsScreenUi?,
) {
Log.d("[Testing]", "Starting ")
Column(
modifier = Modifier.align(Alignment.Center),
horizontalAlignment = Alignment.CenterHorizontally
) {
dialogContentState?.let { data ->
val (initialCard, cardsList) = data
val pagerState = rememberPagerState(
pageCount = {
cardsList.size
}
)
val screenWidth = LocalConfiguration.current.screenWidthDp.dp
val pageWidth = remember { 300.dp }
val sidePadding = remember { (screenWidth - pageWidth) / 2 }
HorizontalPager(
state = pagerState,
pageSpacing = 12.dp,
pageSize = PageSize.Fixed(pageWidth),
contentPadding = PaddingValues(horizontal = sidePadding)
) { page ->
// Page content can go here (e.g., display card content)
}
Spacer(modifier = Modifier.height(22.dp))
DotStepper(count = pagerState.pageCount, count2 = pagerState.currentPage)
}
}
}
@Composable
fun DotStepper(count: Int, count2: Int) {
Log.d("[Testing]", "Horizontal Pager $count and ${count2}")
}
为了防止不必要的重组,请将
pagerState.currentPage
和 pagerState.pageCount
存储在记忆块中,以仅观察必要的状态变化。
val currentPage by remember { derivedStateOf { pagerState.currentPage } }
val pageCount by remember { derivedStateOf { pagerState.pageCount } }
DotStepper(count = pageCount, count2 = currentPage)