• 使用 Jetpack Compose 实现一个计算器APP


    前言

    上一篇文章中,我们说到打算使用 compose 实现一个计算器 APP,最开始打算做一个经典的 LCD 基础计算器,后来觉得好像没啥特色,最终决定还是改成仿微软计算器。

    不过,微软计算器的功能太多了,仿制的工程量不小,所以我打算只仿我认为最核心的两个模式:标准模式和程序员模式。

    另外,这篇文章只说 UI 实现,具体的运算逻辑可以自行查看源码。

    功能特性

    是否支持功能
    基础四则运算(标准、程序员)
    无限输入(标准)
    % , 1/x , x² , √x 扩展运算(标准)
    运算过程历史记录(标准)
    二进制、八进制、十进制、十六进制随意切换并实时换算(程序员)
    位运算:左移、右移(程序员)
    逻辑运算:AND、OR、NOT、XOR(程序员)
    无限连续计算(标准、程序员)
    支持悬浮窗计算器,可调整位置、大小、透明度(标准)
    符合人体握持习惯的横屏键盘
    旋转手机自动切换标准和程序员键盘
    深色模式
    酷炫的数字动效与振动反馈

    注意:

    1. 标准模式使用 BigDecimal 计算,所以理论支持无限位数数字计算
    2. 程序员模式因为涉及到二进制计算,所以采用 64 位储存大小,故不支持无限位数计算
    3. 程序员模式不支持带小数运算,如果运算结果有小数,则会直接抛弃小数部分

    截图

    浅色深色


    标准模式


    标准模式


    历史记录


    历史记录


    程序员模式


    程序员模式


    悬浮窗


    悬浮窗

    项目地址

    github.com/equationl/c…

    欢迎 star

    界面布局

    根据计划,我们需要实现的是微软计算器的标准模式和程序员模式。

    标准模式界面方案确定

    首先,确定一下微软计算器标准模式的界面:

    可以看到,它的布局思路为最顶部是菜单,下方紧跟着显示区域,最下面是键盘,键盘又分为功能按键和数字按键,两种按键使用不同的背景颜色作为区分。并且等于按键使用特别的强调颜色。

    先看一下我们简单模仿的布局:

    看起来不错是吧?我也是这样觉得的,但是当我装到实机上时却发现好像不太对劲。

    首先,使用灰色作为背景色,会显得特别晃眼,在观感上十分不理想。

    其次,现在手机屏幕大多数不是 16:9 的比例了,所以会显得显示区域特别小,而按键被拉伸的特别长,用我一朋友的话来说就是,搞得跟个老年机似的。

    这说明,虽然微软计算器的布局在 PC 上看起来不错,但是却不适合手机。

    那么我们不如找一个手机上的计算器进行仿制,于是我将目光放到了手机自带的小米计算器上:

    可以看到,小米计算器和微软计算器在布局上大差不差,但是在某些细节上有所区别。

    例如,小米计算器所有按钮使用统一的背景颜色,依靠按钮文字区分不同按键类型;

    小米计算器的显示区域和按键区域几乎是 1:1 均分,这样不会显得”头重脚轻“。

    好,那么我们就按照这个思路来修改,修改后布局如下:

    这下看起来顺眼多了,装到手机上一样的好看。

    标准模式界面实现

    确定了界面方案,下面就是研究怎么实现布局。

    简单观察布局,无非就是一堆按钮堆叠在一起,但是如果我们真的一个一个按钮堆上去是不是显得有点傻?哈哈,所以这里我们定义一个列表用来存放按键信息,然后遍历这个列表渲染按键UI。

    定义按键信息数据类:

    1. data class KeyBoardData(
    2. /**
    3. * 按键文本
    4. * */
    5. val text: String,
    6. /**
    7. * 设置按钮颜色,设置范围取决于 [isFilled]
    8. * */
    9. val background: Color,
    10. /**
    11. * 按键索引
    12. * */
    13. val index: Int,
    14. /**
    15. * 是否填充该按钮,如果为 true 则 [background] 用于填充该按钮背景;否则,[background] 用于设置该按钮字体颜色
    16. * */
    17. val isFilled: Boolean = false,
    18. /**
    19. * 是否启用按键
    20. * */
    21. val isAvailable: Boolean = true
    22. )
    23. 复制代码

    定义按键信息列表:

    1. @Composable
    2. fun standardKeyBoardBtn(): List> = listOf(
    3. listOf(
    4. KeyBoardData("%", functionColor(), KeyIndex_Percentage),
    5. KeyBoardData("CE", functionColor(), KeyIndex_CE),
    6. KeyBoardData("C", functionColor(), KeyIndex_Clear),
    7. KeyBoardData("⇦", functionColor(), KeyIndex_Back),
    8. ),
    9. listOf(
    10. KeyBoardData("1/x", functionColor(), KeyIndex_Reciprocal),
    11. KeyBoardData("x²", functionColor(), KeyIndex_Pow2),
    12. KeyBoardData("√x", functionColor(), KeyIndex_Sqrt),
    13. KeyBoardData(Operator.Divide.showText, functionColor(), KeyIndex_Divide),
    14. ),
    15. listOf(
    16. KeyBoardData("7", numberColor(), KeyIndex_7),
    17. KeyBoardData("8", numberColor(), KeyIndex_8),
    18. KeyBoardData("9", numberColor(), KeyIndex_9),
    19. KeyBoardData(Operator.MULTIPLY.showText, functionColor(), KeyIndex_Multiply),
    20. ),
    21. listOf(
    22. KeyBoardData("4", numberColor(), KeyIndex_4),
    23. KeyBoardData("5", numberColor(), KeyIndex_5),
    24. KeyBoardData("6", numberColor(), KeyIndex_6),
    25. KeyBoardData(Operator.MINUS.showText, functionColor(), KeyIndex_Minus),
    26. ),
    27. listOf(
    28. KeyBoardData("1", numberColor(), KeyIndex_1),
    29. KeyBoardData("2", numberColor(), KeyIndex_2),
    30. KeyBoardData("3", numberColor(), KeyIndex_3),
    31. KeyBoardData(Operator.ADD.showText, functionColor(), KeyIndex_Add),
    32. ),
    33. listOf(
    34. KeyBoardData("+/-", numberColor(), KeyIndex_NegativeNumber),
    35. KeyBoardData("0", numberColor(), KeyIndex_0),
    36. KeyBoardData(".", numberColor(), KeyIndex_Point),
    37. KeyBoardData("=", equalColor(), KeyIndex_Equal, isFilled = true),
    38. )
    39. )
    40. 复制代码

    这里之所以把按键信息列表定义为 Composable 是因为需要适配深色模式,而深色模式的颜色,只能在 Composable 中拿。

    颜色代码定义如下:

    1. @Composable
    2. fun numberColor(): Color = Color.Unspecified // MaterialTheme.colors.secondary
    3. @Composable
    4. fun functionColor(): Color = MaterialTheme.colors.primary
    5. @Composable
    6. fun equalColor(): Color = MaterialTheme.colors.primaryVariant
    7. 复制代码

    完成了按键信息定义,下面开始编写按键布局:

    1. @Composable
    2. private fun StandardKeyBoard(viewModel: StandardViewModel) {
    3. Column(modifier = Modifier.fillMaxSize()) {
    4. for (btnRow in standardKeyBoardBtn()) {
    5. Row(modifier = Modifier
    6. .fillMaxWidth()
    7. .weight(1f)) {
    8. for (btn in btnRow) {
    9. Row(modifier = Modifier.weight(1f)) {
    10. KeyBoardButton(
    11. text = btn.text,
    12. onClick = { viewModel.dispatch(StandardAction.ClickBtn(btn.index)) },
    13. backGround = btn.background,
    14. paddingValues = PaddingValues(0.5.dp),
    15. isFilled = btn.isFilled
    16. )
    17. }
    18. }
    19. }
    20. }
    21. }
    22. }
    23. @OptIn(ExperimentalMaterialApi::class)
    24. @Composable
    25. private fun KeyBoardButton(
    26. text: String,
    27. onClick: () -> Unit,
    28. backGround: Color = Color.White,
    29. isFilled: Boolean = false,
    30. paddingValues: PaddingValues = PaddingValues(0.dp)
    31. ) {
    32. Card(
    33. onClick = { onClick() },
    34. modifier = Modifier
    35. .fillMaxSize()
    36. .padding(paddingValues),
    37. backgroundColor = if (isFilled) backGround else MaterialTheme.colors.surface,
    38. shape = MaterialTheme.shapes.large,
    39. elevation = 0.dp,
    40. border = BorderStroke(0.dp, Color.Transparent)
    41. ) {
    42. Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {
    43. Text(text, fontSize = 32.sp, color = if (isFilled) Color.Unspecified else backGround)
    44. }
    45. }
    46. }
    47. 复制代码

    然后是显示区域布局:

    1. @OptIn(ExperimentalAnimationApi::class)
    2. @Composable
    3. private fun ShowScreen(viewModel: StandardViewModel) {
    4. val viewState = viewModel.viewStates
    5. val inputScrollerState = rememberScrollState()
    6. val showTextScrollerState = rememberScrollState()
    7. Column(
    8. Modifier
    9. .fillMaxWidth()
    10. .fillMaxHeight(0.4f)
    11. .noRippleClickable { viewModel.dispatch(StandardAction.ToggleHistory(true)) }
    12. ,
    13. horizontalAlignment = Alignment.End,
    14. verticalArrangement = Arrangement.SpaceAround
    15. ) {
    16. // 上一个计算结果
    17. AnimatedContent(targetState = viewState.lastShowText) { targetState: String ->
    18. SelectionContainer {
    19. AutoSizeText(
    20. text = targetState,
    21. fontSize = ShowSmallFontSize,
    22. fontWeight = FontWeight.Light,
    23. color = if (MaterialTheme.colors.isLight) Color.Unspecified else MaterialTheme.colors.primary,
    24. modifier = Modifier
    25. .padding(horizontal = 12.dp)
    26. .padding(bottom = 16.dp)
    27. .alpha(0.5f),
    28. minSize = 10.sp
    29. )
    30. }
    31. }
    32. Column(horizontalAlignment = Alignment.End) {
    33. // 计算公式
    34. AnimatedContent(targetState = viewState.showText) { targetState: String ->
    35. Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) {
    36. if (showTextScrollerState.value != showTextScrollerState.maxValue) {
    37. Icon(
    38. imageVector = Icons.Outlined.ArrowLeft,
    39. contentDescription = "scroll left",
    40. modifier = Modifier.absoluteOffset(x = scrollToLeftAnimation(-10f).dp)
    41. )
    42. }
    43. Row(
    44. modifier = Modifier
    45. .padding(vertical = 8.dp)
    46. .padding(end = 8.dp)
    47. .horizontalScroll(showTextScrollerState, reverseScrolling = true)
    48. ) {
    49. SelectionContainer {
    50. Text(
    51. text = if (targetState.length > 5000) "数字过长" else targetState,
    52. fontSize = ShowNormalFontSize,
    53. fontWeight = FontWeight.Light,
    54. color = if (MaterialTheme.colors.isLight) Color.Unspecified else MaterialTheme.colors.primary
    55. )
    56. }
    57. }
    58. }
    59. }
    60. // 输入值或计算结果
    61. AnimatedContent(
    62. targetState = viewState.inputValue,
    63. transitionSpec = {
    64. if (targetState.length > initialState.length) {
    65. slideInVertically { height -> height } + fadeIn() with
    66. slideOutVertically { height -> -height } + fadeOut()
    67. } else {
    68. slideInVertically { height -> -height } + fadeIn() with
    69. slideOutVertically { height -> height } + fadeOut()
    70. }.using(
    71. SizeTransform(clip = false)
    72. )
    73. }
    74. ) { targetState: String ->
    75. Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) {
    76. if (inputScrollerState.value != inputScrollerState.maxValue) {
    77. Icon(
    78. imageVector = Icons.Outlined.ArrowLeft,
    79. contentDescription = "scroll left",
    80. modifier = Modifier.absoluteOffset(x = scrollToLeftAnimation(-10f).dp)
    81. )
    82. }
    83. Row(modifier = Modifier
    84. .padding(vertical = 8.dp)
    85. .padding(end = 8.dp)
    86. .horizontalScroll(inputScrollerState, reverseScrolling = true)
    87. ) {
    88. SelectionContainer {
    89. Text(
    90. text = targetState.formatNumber(formatDecimal = viewState.isFinalResult),
    91. fontSize = InputLargeFontSize,
    92. fontWeight = FontWeight.Bold,
    93. color = if (MaterialTheme.colors.isLight) Color.Unspecified else MaterialTheme.colors.primary
    94. )
    95. }
    96. LaunchedEffect(Unit) {
    97. inputScrollerState.scrollTo(0)
    98. }
    99. }
    100. }
    101. }
    102. }
    103. }
    104. }
    105. 复制代码

    由于标准模式使用 BigDecimal 进行计算,所以理论上可以输入无限长的数字,因此这里需要处理一下字符溢出。

    原先我采用的是自适应缩放输入数字,即当输入文字即将超出屏幕时,自动缩小文字字号,确保文字能够完整显示,小米计算器和微软计算器都是这种处理方案。

    但是这样处理的话,不用我上代码,相信各位读者已经发现问题了吧?

    既然我说了文字是无限长度的,那么,即使我能一直缩放字体大小,那么到最后,字体也只是缩成一坨完全无法辨认的像素点。

    所以这个方案不可行,我们应该换一种方案,那换成可以水平滚动或许要友好一点,

    所以我给显示文本的地方增加了 .horizontalScroll(inputScrollerState, reverseScrolling = true),并且在每次重组时将其滚动到最后,确保最新输入的内容始终在屏幕可见区域:

    1. LaunchedEffect(Unit) {
    2. inputScrollerState.scrollTo(0)
    3. }
    4. 复制代码

    这里使用 scrollTo(0) 是由于我们设置了 reverseScrolling = true,而之所以要这么设置是因为我们无法或者说不能方便的拿到这个水平滚动区域的最大值,索性直接反转它,然后滚动到 0 即为滚动到最后。

    上面代码中还有一段:

    1. if (inputScrollerState.value != inputScrollerState.maxValue) {
    2. Icon(
    3. imageVector = Icons.Outlined.ArrowLeft,
    4. contentDescription = "scroll left",
    5. modifier = Modifier.absoluteOffset(x = scrollToLeftAnimation(-10f).dp)
    6. )
    7. }
    8. 复制代码

    此处表示的是,当显示文本超出可视区域时且不在最开头,则显示一个指向左边的图标,提示用户此时有未显示完的文字,可以滚动查看。

    对了,我还给这个图标加了个简单的位移动画:

    1. @Composable
    2. fun scrollToLeftAnimation(targetValue: Float = -5f): Float {
    3. val infiniteTransition = rememberInfiniteTransition()
    4. val slipUpYAnimation by infiniteTransition.animateFloat(
    5. initialValue = 0f,
    6. targetValue = targetValue,
    7. animationSpec = infiniteRepeatable(
    8. animation = tween(2000),
    9. repeatMode = RepeatMode.Restart
    10. )
    11. )
    12. return slipUpYAnimation
    13. }
    14. 复制代码

    最终效果如下:

    程序员模式界面确定

    老规矩,先看微软计算器的程序模式是什么样子的:

    可以看到,程序员模式相比于标准模式多了几个数字(A、B、C……)用于表示十六进制,并且由于可以切换进制,还需要禁用某些数字按键,例如在八进制时需要禁用 8 和 9 。

    其他就是一些功能按键的不同。

    但是微软的程序员模式计算器支持的运算非常多,还支持很多扩展功能,这里我们就不仿这么多了,我们只实现它的多进制支持、位移、位逻辑运算和基础的四则运算即可,同时不再支持小数运算。

    并且,为了让计算器显得更加人性化,我们决定把程序员模式做成横屏显示,大致显示效果如下:

    从预览来看似乎挺不错的,但是,当装到实机上时出现了和标准计算器一样的问题:由于手机比例各不相同,按键会被拉伸成很奇怪的样子,而且显示区域将无法显示完所有文本。

    那么或许程序员模式不适合使用现有的布局模式。

    我想了想,想到了两种布局方案:

    第一种采用两边放按键,中间放显示屏的布局方式;第二种使用显示区域和按键区域均分屏幕的方案。

    最终,考虑到其实如果手机是横屏的话,一般都是双手握持手机的两端,这么一来似乎方案1更加合理,方案2可能会被左手遮挡住按键布局,并且右手在握持时不方便点击比较靠近中间的按键。

    但是这里方案1也有一个问题,就是一般人的惯用手都是右手,所以应该把点击频率更高的数字按键放到右边,点击频率相对较低的功能按键放到左手边。

    最终成品如下:

    程序员模式界面实现

    程序员模式实现过程与标准模式大差不差,同样是先定义按键信息列表,这里我们把功能按键和数字按键分开定义:

    1. @Composable
    2. fun programmerNumberKeyBoardBtn(): List> = listOf(
    3. listOf(
    4. KeyBoardData("D", numberColor(), KeyIndex_D),
    5. KeyBoardData("E", numberColor(), KeyIndex_E),
    6. KeyBoardData("F", numberColor(), KeyIndex_F)
    7. ),
    8. listOf(
    9. KeyBoardData("A", numberColor(), KeyIndex_A),
    10. KeyBoardData("B", numberColor(), KeyIndex_B),
    11. KeyBoardData("C", numberColor(), KeyIndex_C)
    12. ),
    13. listOf(
    14. KeyBoardData("7", numberColor(), KeyIndex_7),
    15. KeyBoardData("8", numberColor(), KeyIndex_8),
    16. KeyBoardData("9", numberColor(), KeyIndex_9)
    17. ),
    18. listOf(
    19. KeyBoardData("4", numberColor(), KeyIndex_4),
    20. KeyBoardData("5", numberColor(), KeyIndex_5),
    21. KeyBoardData("6", numberColor(), KeyIndex_6)
    22. ),
    23. listOf(
    24. KeyBoardData("1", numberColor(), KeyIndex_1),
    25. KeyBoardData("2", numberColor(), KeyIndex_2),
    26. KeyBoardData("3", numberColor(), KeyIndex_3)
    27. ),
    28. listOf(
    29. KeyBoardData("<<", functionColor(), KeyIndex_Lsh),
    30. KeyBoardData("0", numberColor(), KeyIndex_0),
    31. KeyBoardData(">>", functionColor(), KeyIndex_Rsh)
    32. )
    33. )
    34. @Composable
    35. fun programmerFunctionKeyBoardBtn(): List> = listOf(
    36. listOf(
    37. KeyBoardData("C", functionColor(), KeyIndex_Clear),
    38. KeyBoardData("⇦", functionColor(), KeyIndex_Back)
    39. ),
    40. listOf(
    41. KeyBoardData("CE", functionColor(), KeyIndex_CE),
    42. KeyBoardData(Operator.Divide.showText, functionColor(), KeyIndex_Divide)
    43. ),
    44. listOf(
    45. KeyBoardData("NOT", functionColor(), KeyIndex_Not),
    46. KeyBoardData(Operator.MULTIPLY.showText, functionColor(), KeyIndex_Multiply)
    47. ),
    48. listOf(
    49. KeyBoardData("XOR", functionColor(), KeyIndex_XOr),
    50. KeyBoardData(Operator.MINUS.showText, functionColor(), KeyIndex_Minus)
    51. ),
    52. listOf(
    53. KeyBoardData("AND", functionColor(), KeyIndex_And),
    54. KeyBoardData(Operator.ADD.showText, functionColor(), KeyIndex_Add)
    55. ),
    56. listOf(
    57. KeyBoardData("OR", functionColor(), KeyIndex_Or),
    58. KeyBoardData("=", equalColor(), KeyIndex_Equal, isFilled = true)
    59. )
    60. )
    61. 复制代码

    然后,在渲染界面时,需要判断一下当前数字按键是否启用,如果不启用则更改颜色,并且禁止点击:

    1. @Composable
    2. private fun FunctionKeyBoard(viewModel: ProgrammerViewModel) {
    3. val viewState = viewModel.viewStates
    4. Column(modifier = Modifier.fillMaxSize()) {
    5. for (btnRow in programmerFunctionKeyBoardBtn()) {
    6. Row(modifier = Modifier
    7. .fillMaxWidth()
    8. .weight(1f)) {
    9. for (btn in btnRow) {
    10. // 判断该按键是否需要启用
    11. val isAvailable = if (btn.isAvailable) {
    12. btn.index !in viewState.inputBase.forbidBtn
    13. }
    14. else {
    15. false
    16. }
    17. Row(modifier = Modifier.weight(1f)) {
    18. KeyBoardButton(
    19. text = btn.text,
    20. onClick = { viewModel.dispatch(ProgrammerAction.ClickBtn(btn.index)) },
    21. isAvailable = isAvailable,
    22. backGround = btn.background,
    23. isFilled = btn.isFilled,
    24. paddingValues = PaddingValues(0.5.dp)
    25. )
    26. }
    27. }
    28. }
    29. }
    30. }
    31. }
    32. @OptIn(ExperimentalMaterialApi::class)
    33. @Composable
    34. private fun KeyBoardButton(
    35. text: String,
    36. onClick: () -> Unit,
    37. isAvailable: Boolean = true,
    38. backGround: Color = Color.White,
    39. isFilled: Boolean = false,
    40. paddingValues: PaddingValues = PaddingValues(0.dp)
    41. ) {
    42. Card(
    43. onClick = { onClick() },
    44. modifier = Modifier
    45. .fillMaxSize()
    46. .padding(paddingValues),
    47. backgroundColor = if (isFilled) backGround else MaterialTheme.colors.surface,
    48. shape = MaterialTheme.shapes.large,
    49. elevation = 0.dp,
    50. border = BorderStroke(0.dp, Color.Transparent),
    51. enabled = isAvailable // 是否可以点击
    52. ) {
    53. Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {
    54. Text(
    55. text,
    56. fontSize = 24.sp,
    57. color = if (isAvailable) { // 根据是否启用设置按键文本颜色
    58. if (isFilled) Color.Unspecified else backGround
    59. } else {
    60. if (MaterialTheme.colors.isLight) Color.LightGray else Color.DarkGray
    61. }
    62. )
    63. }
    64. }
    65. }
    66. 复制代码

    其中的 inputBase.forbidBtn 是我定义的,当前使用进制需要禁用的按键索引:

    1. enum class InputBase(val number: Int, val forbidBtn: List<Int>) {
    2. HEX(16, listOf()),
    3. DEC(
    4. 10, listOf(
    5. KeyIndex_A,
    6. KeyIndex_B,
    7. KeyIndex_C,
    8. KeyIndex_D,
    9. KeyIndex_E,
    10. KeyIndex_F
    11. )
    12. )
    13. // ......
    14. }
    15. 复制代码

    例如当前使用的是十进制则禁用 A B C D E F 按键。

    最后,说一下我是怎么分配不同组件的占用尺寸的:

    1. @Composable
    2. fun ProgrammerScreen(
    3. viewModel: ProgrammerViewModel = hiltViewModel()
    4. ) {
    5. Row(modifier = Modifier.fillMaxWidth(),
    6. horizontalArrangement = Arrangement.SpaceBetween) {
    7. // 左侧键盘
    8. Row(modifier = Modifier.weight(1.3f)) {
    9. FunctionKeyBoard(viewModel = viewModel)
    10. }
    11. Divider(modifier = Modifier
    12. .fillMaxHeight()
    13. .width(1.dp)
    14. .padding(vertical = 16.dp, horizontal = 0.dp))
    15. // 显示数据
    16. Row(modifier = Modifier.weight(2f)) {
    17. CenterScreen(viewModel = viewModel)
    18. }
    19. Divider(modifier = Modifier
    20. .fillMaxHeight()
    21. .width(1.dp)
    22. .padding(vertical = 16.dp, horizontal = 0.dp))
    23. // 右侧键盘
    24. Row(modifier = Modifier.weight(1.5f)) {
    25. NumberBoard(viewModel = viewModel)
    26. }
    27. }
    28. }
    29. 复制代码

    通过将三个不同的组件: FunctionKeyBoardCenterScreenNumberBoard 包裹在 Row 中,并设置不同的 weight 权重来实现三个组件按照比例完全占满屏幕宽度。

    其他实现细节

    自适应填充满屏幕

    上面我们提到过,使用 AndroidStudio 预览的尺寸比例是 16:9,但是实际现在很多手机都不是 16:9 的比例了,导致预览时看起来布局很和谐,但是一旦安装到手机上就会被拉伸的很难看。

    会出现这种情况是因为我在前期编写布局代码时,使用了硬编码尺寸,例如,标准计算器模式我将显示数字区域高度硬编码为 150 dp,这样虽然在 16:9 的设备上看起来很和谐,但是放到我手机上(比例 21:9)就显得显示区域非常小,而按键因为需要填充满屏幕则会被拉伸的特别大,特别难看。

    最终我的解决方案是固定各个组件的占用比例,并且不硬编码他们的尺寸。

    例如,对于标准模式的显示区域,我将其包裹在一个 Column 中,并设置 modifier 属性:

    1. Column(
    2. Modifier
    3. .fillMaxWidth()
    4. .fillMaxHeight(0.4f)
    5. ,
    6. // ......
    7. ) {
    8. // ......
    9. }
    10. 复制代码

    因为显示区域的上级组件设置了 fillMaxSize ,所以此时显示区域会填充满屏幕宽度,并填充全屏幕的 40% 高度,也就是说,不管设备尺寸是多大,现在显示区域都会恒定填充设备的 40% 高度和所有宽度。

    对了,这里插一句,其实使用 40% 宽度后会显得显示区域特别空旷,但是小米计算器不也是这么个比例吗?为什么它不会显得空旷呢?那是因为小米在显示区域上面加了个实时的历史记录显示,哈哈,所以我也给加上了,大概效果是这样的:

    对了X2,这里只用更改显示区域,而按键区域会根据可用空间自适应调整大小,并且能确保所有按键尺寸一致。

    因为按键布局在编写时给每一行都设置了权重为 1 ,用时每行中的每个按键也设置了权重为 1 :.weight(1f) 。所以最终所有按键会均分所有可用的尺寸。

    历史记录遮罩层

    微软计算器点击顶部菜单的历史记录图标后会从最底下缓慢上升一个遮罩层显示历史记录列表,并且这个遮罩层只会上升到按键的高度,不会超出按键区域,遮住显示区域。

    这个效果其实也非常好实现:

    1. Box(Modifier.fillMaxSize()) {
    2. val isShowHistory = viewState.historyList.isEmpty() // 通过当前状态中历史记录列表是否为空来判断是否应该显示历史记录遮罩层
    3. // 按键组件
    4. StandardKeyBoard(viewModel)
    5. AnimatedVisibility(
    6. visible = isShowHistory,
    7. enter = slideInVertically(initialOffsetY = { it }) + fadeIn(),
    8. exit = slideOutVertically(targetOffsetY = { it }) + fadeOut()
    9. ) {
    10. // 历史记录组件
    11. HistoryWidget(
    12. // ......
    13. )
    14. }
    15. }
    16. 复制代码

    将按键和历史记录包裹在同一个 Box 中。

    其中按键始终可见,历史记录是否显示则却决于 isShowHistory 状态,并且将历史记录组件包裹在 AnimatedVisibility 中。

    AnimatedVisibility 组件会为被它包裹的 content 添加由 enterexit 指定的动画。

    例如这里就指定显示动画使用垂直滑入加淡入效果,退出则为垂直滑出加淡出效果。

    滑入的起始 Y 坐标为最大高度(fullHeight)即屏幕底部,initialOffsetY 这个 lambda 的参数 it 表示的就是当前的最大高度。

    滑出的目标 Y 坐标也为最大高度。

    这样就能实现微软计算器的滑动效果了:

    可滚动布局的一个BUG

    在 实现标准模式界面 一节中,我们提到最终采用了可水平滚动来处理文本溢出显示区域。

    但是经过我实际测试,当文本长度达到一定的长度时,会直接闪退:

    1. Process: com.equationl.calculator_compose, PID: 2424
    2. java.lang.IllegalArgumentException: Can't represent a size of 507896 in Constraints
    3. at androidx.compose.ui.unit.Constraints$Companion.bitsNeedForSize(Constraints.kt:403)
    4. at androidx.compose.ui.unit.Constraints$Companion.createConstraints-Zbe2FdA$ui_unit_release(Constraints.kt:366)
    5. at androidx.compose.ui.unit.ConstraintsKt.Constraints(Constraints.kt:433)
    6. at androidx.compose.ui.unit.ConstraintsKt.Constraints$default(Constraints.kt:418)
    7. at androidx.compose.foundation.text.TextDelegate.layoutText-K40F9xA(TextDelegate.kt:198)
    8. at androidx.compose.foundation.text.TextDelegate.layout-NN6Ew-U(TextDelegate.kt:241)
    9. at androidx.compose.foundation.text.TextController$measurePolicy$1.measure-3p2s80s(CoreText.kt:314)
    10. at androidx.compose.ui.node.InnerPlaceable.measure-BRTryo0(InnerPlaceable.kt:44)
    11. at androidx.compose.ui.graphics.SimpleGraphicsLayerModifier.measure-3p2s80s(GraphicsLayerModifier.kt:405)
    12. at androidx.compose.ui.node.ModifiedLayoutNode.measure-BRTryo0(ModifiedLayoutNode.kt:53)
    13. at androidx.compose.ui.node.LayoutNode$performMeasure$1.invoke(LayoutNode.kt:1428)
    14. at androidx.compose.ui.node.LayoutNode$performMeasure$1.invoke(LayoutNode.kt:1427)
    15. at androidx.compose.runtime.snapshots.Snapshot$Companion.observe(Snapshot.kt:2116)
    16. at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:110)
    17. at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:78)
    18. at androidx.compose.ui.node.OwnerSnapshotObserver.observeMeasureSnapshotReads$ui_release(OwnerSnapshotObserver.kt:66)
    19. at androidx.compose.ui.node.LayoutNode.performMeasure-BRTryo0$ui_release(LayoutNode.kt:1427)
    20. at androidx.compose.ui.node.OuterMeasurablePlaceable.remeasure-BRTryo0(OuterMeasurablePlaceable.kt:94)
    21. at androidx.compose.ui.node.OuterMeasurablePlaceable.measure-BRTryo0(OuterMeasurablePlaceable.kt:75)
    22. at androidx.compose.ui.node.LayoutNode.measure-BRTryo0(LayoutNode.kt:1366)
    23. at androidx.compose.foundation.text.selection.SimpleLayoutKt$SimpleLayout$1.measure-3p2s80s(SimpleLayout.kt:35)
    24. ......
    25. 复制代码

    通过这个错误堆栈,大致可以猜测出闪退是由于文本太大,导致水平滚动也无法测量尺寸导致闪退。

    错误的具体原因目前我还不知道,但是我们可以通过简单的限制最大文本数量避免触发这个问题:

    1. Text(
    2. text = if (targetState.length > 5000) "数字过长" else targetState,
    3. fontSize = ShowNormalFontSize,
    4. fontWeight = FontWeight.Light,
    5. color = if (MaterialTheme.colors.isLight) Color.Unspecified else MaterialTheme.colors.primary
    6. )
    7. 复制代码

    虽然这样就违背了我们设计的可以无限输入数字的特性了。

    总结

    使用 compose 仿其他 APP 的界面相比较于使用传统 xml 可以说是方便的多了,现在 compose 基本也可以完美使用了,就是总还是会有一些奇奇怪怪的小 BUG 让人很烦,就比如我上面说到的这个尺寸溢出闪退的问题。

  • 相关阅读:
    编程前置:句子联想游戏
    进销存记账软件十大品牌合集,看看哪一款适合你
    2023年地理信息系统与遥感专业就业前景与升学高校排名选择
    瞅瞅 Opencv:扫描图像
    5年开发经验,看完这份37W字Java高性能架构,终于拿到架构师薪资
    Mybatis-Plus条件构造器QueryWrapper
    SpringBoot SpringBoot 开发实用篇 4 数据层解决方案 4.3 H2数据库
    kafka生产者异步发送、同步发送、回调异步发送,是什么情况?
    java1.8新特性入门级讲解
    R语言使用order函数对dataframe数据进行排序、基于单个字段(变量)进行降序排序(DESCENDING)
  • 原文地址:https://blog.csdn.net/sinat_17133389/article/details/126931907