val textview = findViewById<TextView>(R.id.textview)
textview.setOnClickListener(clickListener)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener(clickListener)
ClickListener code.
val clickListener = View.OnClickListener {view ->
when (view.getId()) {
R.id.textview -> firstFun()
R.id.button -> secondFun()
}
}
// get reference to button
val btn_click_me = findViewById(R.id.btn_click_me) as Button
// set on-click listener
btn_click_me.setOnClickListener {
Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
}
**i have use kotlin-extension so i can access directly by button id:**
btnSignIN.setOnClickListener {
if (AppUtils.isNetworkAvailable(activity as BaseActivity)) {
if (checkValidation()) {
hitApiLogin()
}
}
}
button.setOnClickListener {
// Do some work here
}
第二:
button.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
// Do some work here
}
})
第三:
button.setOnClickListener(View.OnClickListener { view ->
// Do some work here
})
第四:
class MainActivity : AppCompatActivity(), View.OnClickListener{
lateinit var button : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.button1)
button.setOnClickListener(this)
}
override fun onClick(view: View?) {
when(view?.id){
R.id.button1->{
// do some work here
}
}
}
}
第五:
class MainActivity : AppCompatActivity(){
lateinit var button : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.button1)
button.setOnClickListener(listener)
}
val listener= View.OnClickListener { view ->
when (view.getId()) {
R.id.button1 -> {
// Do some work here
}
}
}
}
六年级
button.setOnClickListener { view ->
// Do some work here
}