2024-01-30|閱讀時間 ‧ 約 28 分鐘

Android x Kotlin 實作課程:打造個人專屬計算機 APP EP5 處理按鈕點擊事件

打造個人專屬計算機 APP 系列文章目錄:
https://vocus.cc/article/65acea9ffd897800019c13dc

課程摘要

本課程學習如何處理按鈕點擊事件並透過 Logcat 日誌輸出資訊確認按鈕邏輯是否正確。

教學影片

若您無法順利觀看教學影片,請先登入您的 YouTube 帳號,然後點擊以下連結加入我們的頻道會員:

  • 一般會員:成為一般會員後,您將能夠觀看我們所提供的一般會員專屬線上課程。
  • 精實會員:成為精實會員後,您將能夠觀看我們所提供的精實會員專屬線上課程。

範例程式碼

MainActivity.kt

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")
}
}
分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.