kotlin 按钮事件_OnClickListners-使用Kotlin触发按钮单击事件| Android与Kotlin

kotlin 按钮事件

The event is a very important part of any application which makes it user intractable. It may be generated when we click on any view in Android. To trigger click events on any view, we have OnClickListners.

该事件是任何使用户难以处理的应用程序中非常重要的部分。 当我们单击Android中的任何视图时,可能会生成它。 要触发任何视图上的点击事件,我们都有OnClickListners

Here are the various ways in which we can use OnClickListners:

这是我们可以使用OnClickListners各种方式

1) Simplest way is writing code under setOnClickListener{ } which you want to execute on button(view) click.

1)最简单的方法是在setOnClickListener {}下编写要在按钮(视图)单击时执行的代码。

button.setOnClickListener{
	Toast.makeText(applicationContext, "You clicked me.", Toast.LENGTH_SHORT).show()
}

button is the id of the Button. We have used <id>.setOnClickListener. This can be achieved using view binding in kotlin which we have discussed in previous article. If you are new to view binding, I suggest you to go through previous article once.

button是Button的ID 。 我们使用了<id> .setOnClickListener 。 这可以使用我们在上一篇文章中讨论过的kotlin中的视图绑定来实现。 如果您不熟悉绑定,那么建议您阅读上一篇文章

2) Kotlin implementation of the Java code

2)Kotlin实现的Java代码

button.setOnClickListener(object: View.OnClickListener {
	override fun onClick(v: View?) {
		textView.text = "Clicked"
		v?.setBackgroundColor(Color.MAGENTA)
	}
}

If you want to use that view during the click event, use this. In this we have an object of view, you can use that view object to make changes to the particular view if required.

如果要在单击事件期间使用该视图,请使用此视图。 在此我们有一个视图对象,您可以根据需要使用该视图对象对特定视图进行更改。

3) Similar to 2 but in kotlin style

3)与2类似,但采用Kotlin风格

button.setOnClickListener({
	v->
	textView.text = "Clicked"
	v.setBackgroundColor(Color.RED)
})

Here v is object of the referenced View.

这里v是引用的View的对象。

4) We can also use it to reference current view in kotlin

4)我们也可以使用它来引用kotlin中的当前视图

button.setOnClickListener{
	textView.text = "Clicked"
	it.setBackgroundColor(Color.RED)
}

Conclusion:

结论:

So in this article, we came to know about various ways in which we can use click events on android views. If you feel any doubt just write down to the comment section.

因此,在本文中,我们了解了可以在android视图上使用click事件的各种方式。 如果您有任何疑问,请写下评论部分。

翻译自: https://www.includehelp.com/kotlin/OnClickListners-trigger-button-click-events-using-kotlin.aspx

kotlin 按钮事件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值