You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用函数或类优化Android三骰子应用的重复代码?

优化Android骰子应用代码:消除重复,提升可维护性

当前代码存在大量重复逻辑,比如每个骰子的视图操作、点数映射、点击事件处理,通过封装数据类和提取通用函数可以大幅精简代码,同时提升可维护性。以下是优化后的完整代码:

优化后的MainActivity代码

package com.example.notfall_kit

import android.os.Bundle
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible

// 封装单个骰子的视图组件与状态
data class DiceView(
    val button: ImageButton,
    val fixedImageView: ImageView,
    var currentValue: Int = 0
)

class MainActivity : AppCompatActivity() {
    private lateinit var rollButton: Button
    // 用列表统一管理三个骰子的封装对象
    private lateinit var diceViews: List<DiceView>
    private val dice = Dice()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 一次性完成所有视图查找,避免重复调用findViewById
        rollButton = findViewById(R.id.wuerfelButton)
        diceViews = listOf(
            DiceView(
                button = findViewById(R.id.imageButtonCenter),
                fixedImageView = findViewById(R.id.imageViewCenter)
            ),
            DiceView(
                button = findViewById(R.id.imageButtonLeft),
                fixedImageView = findViewById(R.id.imageViewLeft)
            ),
            DiceView(
                button = findViewById(R.id.imageButtonRight),
                fixedImageView = findViewById(R.id.imageViewRight)
            )
        )

        // 统一设置所有骰子按钮的点击逻辑
        diceViews.forEach { diceView ->
            diceView.button.setOnClickListener {
                diceView.fixedImageView.isVisible = true
                diceView.button.isVisible = false
            }
        }

        rollButton.setOnClickListener { rollAllDice() }
    }

    private fun rollAllDice() {
        diceViews.forEach { diceView ->
            // 仅对未固定的骰子执行投掷逻辑
            if (diceView.button.isVisible) {
                diceView.currentValue = dice.roll()
                diceView.button.setImageResource(getDiceImageRes(diceView.currentValue))
            }
        }
        checkAndFixDices()
    }

    private fun checkAndFixDices() {
        diceViews.forEach { diceView ->
            // 检查是否满足固定条件(未固定且点数为1或6)
            if (diceView.button.isVisible && (diceView.currentValue == 1 || diceView.currentValue == 6)) {
                diceView.fixedImageView.setImageResource(getDiceImageRes(diceView.currentValue))
            }
        }
    }

    // 通用函数:将骰子点数映射为对应图片资源
    private fun getDiceImageRes(value: Int): Int {
        return when (value) {
            1 -> R.drawable.dice_1
            2 -> R.drawable.dice_2
            3 -> R.drawable.dice_3
            4 -> R.drawable.dice_4
            5 -> R.drawable.dice_5
            6 -> R.drawable.dice_6
            else -> R.drawable.dice_1 // 默认值,防止异常情况
        }
    }
}

优化后的Dice类代码

package com.example.notfall_kit

class Dice(val numSides: Int = 6) {
    fun roll(): Int {
        return (1..numSides).random()
    }
}

优化细节拆解

  1. 封装骰子视图与状态
    创建DiceView数据类,把每个骰子对应的按钮、固定显示视图、当前点数打包在一起,用列表统一管理三个骰子对象,后续通过循环即可完成所有重复操作,无需重复编写三次相同逻辑。

  2. 抽离通用映射逻辑
    将点数转图片资源的逻辑单独提取为getDiceImageRes函数,替代原来三处重复的when语句,后续修改骰子图片只需改动这一处即可。

  3. 统一处理点击事件
    所有骰子按钮的点击逻辑完全一致,直接用forEach循环批量设置监听,避免复制粘贴三次重复代码。

  4. 减少视图查找次数
    在onCreate中一次性完成所有视图的查找并存储为成员变量,避免在投掷、检查固定逻辑中重复调用findViewById,既提升性能又简化代码。

  5. 简化投掷与固定逻辑
    投掷时仅处理未固定的骰子,检查固定条件时通过循环遍历所有骰子,逻辑更清晰,代码量直接缩减近一半。

  6. 简化Dice类调用
    给numSides设置默认值6,因为当前应用仅使用6面骰子,创建Dice对象时无需再传入参数,代码更简洁。

内容的提问来源于stack exchange,提问作者pythonnewbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:40:27