A simple way would be to register a click listener and create a click listener with a lambda expression.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// click listener registered
myButton.setOnClickListener(clickListener)
}
And implement the clickListener
:
private val clickListener: View.OnClickListener = View.OnClickListener { _ ->
// do something here
}
You can replace _
with a name if you need the view to use it. For example, you need to check the id of click listener.
private val clickListener: View.OnClickListener = View.OnClickListener { view ->
if(view.id == login.id) {
// do something here
}
}
Use this code to add onClickListener
in Kotlin
val button : Button = getView()?.findViewById<Button>(R.id.testButton) as Button
button.setOnClickListener {view ->
Toast.makeText(context, "Write your message here", Toast.LENGTH_LONG).show()
}
}
Suppose you have textView to click
text_view.text = "Hello Kotlin";
text_view.setOnClickListener {
val intent = Intent(this@MainActivity, SecondActivity::class.java)
intent.putExtra("key", "Kotlin")
startActivity(intent)
}
There are several different ways to achieve this, as shown by the variety of answers on this question.
To actually assign the listener to the view, you use the same methods as you would in Java:
button.setOnClickListener()
However, Kotlin makes it easy to assign a lambda as a listener:
button.onSetClickListener {
// Listener code
}
Alternatively, if you want to use this listener for multiple views, consider a lambda expression (a lambda assigned to a variable/value for reference):
val buttonClickListener = View.OnClickListener { view ->
// Listener code
}
button.setOnClickListener(buttonClickListener)
another_button.setOnClickListener(buttonClickListener)
findViewById<Button>(R.id.signUp)?.setOnClickListener(
Toast.makeText(mActivity, "Button Clicked", Toast.LENGTH_LONG).show()
)
Method 1:
txtNext.setOnClickListener {
//Code statements
}
Method 2:
class FirstActivity : AppCompatActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first)
txtNext.setOnClickListener(this)
}
override fun onClick(v: View) {
when (v.id) {
R.id.txtNext -> {
//Code statements
}
else -> {
// else condition
}
}
}
}
The easiest way that I know to achieve that is through Kotlin Android Extensions.
On your app/build.gradle
apply plugin: 'kotlin-android-extensions'
If your button is called 'btnAdd', then on your fragment or activity import the following:
import kotlinx.android.synthetic.main.fragment_transactions.btnAdd
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btnAdd.setOnClickListener {
Toast.makeText(context , "Done", 10).show()
}
}
Use below code
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()
}
}
Here's the solution. Your code will like this:
button.setOnClickListener {
//your code here
}
No need to add anything. like below:
val button = findViewById<Button>(R.id.Button)
button.setOnClickListener {
}
There are five ways to use SetOnClickListener:
First:
button.setOnClickListener {
// Do some work here
}
Second:
button.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
// Do some work here
}
})
Third:
button.setOnClickListener(View.OnClickListener { view ->
// Do some work here
})
Forth:
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
}
}
}
}
Fifth:
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
}
}
}
}
Cheers!
For using multiple ids:
textview1.setOnClickListener(clickListener)
textview2.setOnClickListener(clickListener)
Create anonymous class:
private val clickListener: View.OnClickListener = View.OnClickListener { view ->
when (view.id) {
R.id.textview1-> {
Toast.makeText(this, "Clicked 1", Toast.LENGTH_SHORT).show()
}
R.id.textview2-> {
Toast.makeText(this, "Clicked 2", Toast.LENGTH_SHORT).show()
}
}
}
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
val intent =
Intent(this@MainActivity,ThirdActivity::class.java)
intent.putExtra("key", "Kotlin")
startActivity(intent)
}
You can use setOnClickListener like this in Kotlin
button.setOnClickListener(View.OnClickListener {
//code
})
**i have use kotlin-extension so i can access directly by button id:**
btnSignIN.setOnClickListener {
if (AppUtils.isNetworkAvailable(activity as BaseActivity)) {
if (checkValidation()) {
hitApiLogin()
}
}
}
You use like that onclickListener in kotlin
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {
...
}
val saveButton:Button = findViewById(R.id.button_save)
saveButton.setOnClickListener{
// write code for click event
}
with view object
saveButton.setOnClickListener{
view -> // write code for click event
}
button.setOnClickListener {
//write your code here
}
Button OnClickListener implementation from function in android using kotlin.
Very First Create Button View From .xml File
`<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Button2"
android:layout_weight="0.5"/>`
//and create button instance in Activity
private var btn1:Button?=null
or
//For Late Initialization can Follow like this,
private lateinit var btn1:Button
//in onCreate,
btn1=findViewById(R.id.btn1) as Button
btn1?.setOnClickListener { btn1Click() }
//implementing button OnClick event from Function,
private fun btn1Click() {
Toast.makeText(this, "button1", Toast.LENGTH_LONG).show()
}
First you have to get the reference to the View (say Button, TextView, etc.) and set an OnClickListener to the reference using setOnClickListener() method
// 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()
}
Refer Kotlin SetOnClickListener Example for complete Kotlin Android Example where a button is present in an activity and OnclickListener is applied to the button. When you click on the button, the code inside SetOnClickListener block is executed.
Update
Now you can reference the button directly with its id by including the following import statement in Class file. Documentation.
import kotlinx.android.synthetic.main.activity_main.*
and then for the button
btn_click_me.setOnClickListener {
// statements to run when button is clicked
}
Refer Android Studio Tutorial.
First find the button, to prevent the cast from the View
you can use the <>
as follows :
val button = findViewById<Button>(R.id.button);
Once you have an instance of the Button
, you can now attach the click listener as follows :
button.setOnClickListener {
// You code here
}
If you want to simulate the old anonymous way in Kotlin I found this worked perfectly.
btnNewWay!!.setOnClickListener(object:View.OnClickListener {
override fun onClick(v: View?) {
//Your Code Here!
}})
Add clickListener on button like this
btUpdate.setOnClickListener(onclickListener)
add this code in your activity
val onclickListener: View.OnClickListener = View.OnClickListener { view ->
when (view.id) {
R.id.btUpdate -> updateData()
}
}
Add in build.gradle module file
android {
...
buildFeatures {
viewBinding true
}
}
For Activity add
private lateinit var binding: ResultProfileBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ResultProfileBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
}
Add on click
binding.button.setOnClickListener { Log.d("TAG", "Example") }
Here is an example on how to use the onClickListener in Kotlin
button1.setOnClickListener(object : View.OnClickListener{
override fun onClick(v: View?) {
//Your code here
}})
In case anyone else wants to achieve this while using binding. If the id of your view is button_save then this code can be written, taking advantage of the kotlin apply syntax
binding.apply {
button_save.setOnClickListener {
//dosomething
}
}
Take note binding is the name of the binding instance created for an xml file . Full code is below if you are writing the code in fragment. Activity works similarly
private lateinit var binding: FragmentProfileBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentProfileBinding.inflate(inflater, container, false)
return binding.root
}
// onActivityCreated is deprecated in fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
button_save.setOnClickListener {
//dosomething
}
}
}
Simply you can get OnClickListener in kotlin
view1.setOnClickListener{
//body
}
var tv = findViewById(R.id.tv)
as TextView
tv.setOnClickListener {
val i = Intent(this@MainActivity, SecondActivity::class.java)
startActivity(i)
finish()
}
I see a lot of suggestions here, but this collection is missing the following.
button.setOnClickListener(::onButtonClicked)
and in the current class we have a method like this:
private fun onButtonClicked(view: View) {
// do stuff
}
Simply do as below :
button.setOnClickListener{doSomething()}
Source: Stackoverflow.com