我的问题
写MVI也有一段时间了,最近碰到一个导航有点不按套路出牌,一下子懵逼了,具体效果看下图:
第一眼看到这个UI简单啊,不就是一个Row包含TabRow和一个Image不就可以了吗?,可具体实现下来发现TabRow的item宽度默认是用最长的那个来进行平均分配的,这样就会导致以下问题:
我的优化
一开始想到的就是自定View来解决,想到需要处理page的滑动关联,逛了以下官网发现TopAppBar长得挺像,最终直接copy一份稍作修改如下即可解决(当然自己自定义View再去设置关联也是一样)。
TopAppBar(
modifier = Modifier
.height(ConvertUtils.value2dp(R.dimen.dp_32).dp)
.fillMaxWidth(),
//标题导航
title = {
Row(
modifier = Modifier
.fillMaxSize()
.wrapContentSize(Alignment.CenterStart)
) {
mViewModel.mTopNavigationTitle.forEachIndexed { index, title ->
if (mViewModel.mPagerState.value.currentPage == index) {
Box(
modifier = Modifier
.fillMaxHeight()
.padding(
start = ConvertUtils.value2dp(R.dimen.dp_6).dp,
end = ConvertUtils.value2dp(R.dimen.dp_6).dp
)
.clickable {
CoroutineScope(Dispatchers.Main).launch {
mViewModel.mPagerState.value.scrollToPage(index)
}
}, contentAlignment = Alignment.Center
) {
Text(
title,
fontWeight = FontWeight.Bold,
fontSize = ConvertUtils.value2sp(R.dimen.sp_10).sp,
color = Color(0xFF4A60B6),
textAlign = TextAlign.Center
)
Box(
modifier = Modifier.fillMaxHeight(),
contentAlignment = Alignment.BottomCenter
) {
Spacer(
modifier = Modifier
.height(ConvertUtils.value2dp(R.dimen.dp_1).dp)
.width(ConvertUtils.value2dp(R.dimen.dp_20).dp)
.background(
Color(0xFF4A60B6)
)
)
}
}
} else {
Box(
modifier = Modifier
.fillMaxHeight()
.padding(
start = ConvertUtils.value2dp(R.dimen.dp_6).dp,
end = ConvertUtils.value2dp(R.dimen.dp_6).dp
)
.clickable {
CoroutineScope(Dispatchers.Main).launch {
mViewModel.mPagerState.value.scrollToPage(index)
}
}, contentAlignment = Alignment.Center
) {
Text(
title,
fontWeight = FontWeight.Bold,
fontSize = ConvertUtils.value2sp(R.dimen.sp_10).sp,
color = Color(0xFFc7c7c7),
textAlign = TextAlign.Center
)
}
}
}
}
},
//信息按钮
actions = {
IconButton(onClick = {
}) {
Image(
painter = painterResource(R.mipmap.ic_msg),
contentDescription = "",
modifier = Modifier.size(ConvertUtils.value2dp(R.dimen.dp_14).dp)
)
}
},
//背景色
backgroundColor = Color(0xFF111C2E),
//内容颜色
contentColor = Color(0xFFc7c7c7),
)
//mPagerState滑动回调
LaunchedEffect(mViewModel.mPagerState.value) {
// Collect from the a snapshotFlow reading the currentPage
snapshotFlow { mViewModel.mPagerState.value.currentPage }.collect { page ->
Logger.d("滑动到$page")
mViewModel.mPageIndex.value = page
}
}
//页面内容
HorizontalPager(
count = 3,
state = mViewModel.mPagerState.value,
modifier = Modifier.weight(3f)
) { page ->
when (page) {
0 -> {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
Spacer(modifier = Modifier.height(ConvertUtils.value2dp(R.dimen.dp_14).dp))
socializeItemView(true)
Spacer(modifier = Modifier.height(ConvertUtils.value2dp(R.dimen.dp_14).dp))
socializeItemView(false)
Spacer(modifier = Modifier.height(ConvertUtils.value2dp(R.dimen.dp_14).dp))
socializeItemView(true)
}
}
1 -> Text(text = "好友")
2 -> Text(text = "我的作品")
}
}
Spacer(modifier = Modifier.size(ConvertUtils.value2dp(R.dimen.dp_11).dp))
}