【打造個人專屬計算機 APP】 系列文章目錄:
https://vocus.cc/article/65acea9ffd897800019c13dc
private lateinit var processTextView: TextView
private lateinit var resultTextView: TextView
onCreate
processTextView = binding.processTextView
resultTextView = binding.resultTextVie
//binding.button0.setOnClickListener { ... }
//binding.button1.setOnClickListener { ... }
val buttons = listOf(
binding.button0,
binding.button1,
binding.button2,
binding.button3,
binding.button4,
binding.button5,
binding.button6,
binding.button7,
binding.button8,
binding.button9,
binding.buttonAllClear,
binding.buttonToggleSign,
binding.buttonDivide,
binding.buttonBackspace,
binding.buttonMultiply,
binding.buttonMinus,
binding.buttonPlus,
binding.buttonEquals,
binding.buttonDot
)
buttons.forEach { button ->
button.setOnClickListener { onButtonClick(button) }
}
}
onButtonClick
fun onButtonClick(button: Button) {
// 獲取按鈕的文字或其他相關屬性
val buttonText = button.text.toString()
Log.d("HKT","buttonText: $buttonText")
}
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var processTextView: TextView
private lateinit var resultTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
processTextView = binding.processTextView
resultTextView = binding.resultTextView
val buttons = listOf(
binding.button0,
binding.button1,
binding.button2,
binding.button3,
binding.button4,
binding.button5,
binding.button6,
binding.button7,
binding.button8,
binding.button9,
binding.buttonAllClear,
binding.buttonToggleSign,
binding.buttonDivide,
binding.buttonBackspace,
binding.buttonMultiply,
binding.buttonMinus,
binding.buttonPlus,
binding.buttonEquals,
binding.buttonDot
)
buttons.forEach { button ->
button.setOnClickListener { onButtonClick(button) }
}
}
private fun onButtonClick(button: AppCompatButton) {
val buttonText = button.text.toString()
Log.d("HKT","buttonText: $buttonText")
}
}