【打造個人專屬計算機 APP】 系列文章目錄:
https://vocus.cc/article/65acea9ffd897800019c13dc
本課程學習如何處理按鈕點擊事件並透過 Logcat 日誌輸出資訊確認按鈕邏輯是否正確。
若您無法順利觀看教學影片,請先登入您的 YouTube 帳號,然後點擊以下連結加入我們的頻道會員:
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")
}
}