Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

216
Visualizações
Android - How to achieve setOnClickListener in Kotlin?

I wanted to know that how we set basic onClickListener in Kotlin for Android Development.

over 4 years ago · Santiago Trujillo
32 Respostas
Responde à pergunta

0

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()
        }
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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()
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

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
}
over 4 years ago · Santiago Trujillo Relatório

0

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()
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

You use like that onclickListener in kotlin

val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {  
...
}
over 4 years ago · Santiago Trujillo Relatório

0

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)
}
over 4 years ago · Santiago Trujillo Relatório

0

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
            }})
over 4 years ago · Santiago Trujillo Relatório

0

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
}
over 4 years ago · Santiago Trujillo Relatório

0

findViewById<Button>(R.id.signUp)?.setOnClickListener(
    Toast.makeText(mActivity, "Button Clicked", Toast.LENGTH_LONG).show()
)
over 4 years ago · Santiago Trujillo Relatório

0

Simply you can get OnClickListener in kotlin

view1.setOnClickListener{

//body 

}
over 4 years ago · Santiago Trujillo Relatório

0

**i have use kotlin-extension so i can access directly by button id:**


btnSignIN.setOnClickListener {
            if (AppUtils.isNetworkAvailable(activity as BaseActivity)) {
                if (checkValidation()) {

                    hitApiLogin()
                }
            }
        }
over 4 years ago · Santiago Trujillo Relatório

0

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
        }
    }
  }
}
over 4 years ago · Santiago Trujillo Relatório

0

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()
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

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!
    }})
over 4 years ago · Santiago Trujillo Relatório

0

Simply do as below :

button.setOnClickListener{doSomething()}

over 4 years ago · Santiago Trujillo Relatório

0

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()


        }
    }
over 4 years ago · Santiago Trujillo Relatório

0

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)
over 4 years ago · Santiago Trujillo Relatório

0

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
}
over 4 years ago · Santiago Trujillo Relatório

0

You can use setOnClickListener like this in Kotlin

button.setOnClickListener(View.OnClickListener {        
       //code
})
over 4 years ago · Santiago Trujillo Relatório

0

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 {

}
over 4 years ago · Santiago Trujillo Relatório

0

    val button = findViewById<Button>(R.id.button)
    button.setOnClickListener {
        val intent = 
    Intent(this@MainActivity,ThirdActivity::class.java)
        intent.putExtra("key", "Kotlin")
        startActivity(intent)
    }
over 4 years ago · Santiago Trujillo Relatório

0

   button.setOnClickListener {
          //write your code here
   }
over 4 years ago · Santiago Trujillo Relatório

0

var tv = findViewById(R.id.tv) as TextView

    tv.setOnClickListener {
       val i = Intent(this@MainActivity, SecondActivity::class.java)
       startActivity(i)
       finish()
    }
over 4 years ago · Santiago Trujillo Relatório

0

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
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

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
})

Fourth:

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!

over 4 years ago · Santiago Trujillo Relatório

0

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") }
over 4 years ago · Santiago Trujillo Relatório

0

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
     }
     }
 }
over 4 years ago · Santiago Trujillo Relatório

0

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()
    }
over 4 years ago · Santiago Trujillo Relatório

0

Best for achieve click listener in Kotlin(Mean Without findview by id you can click or intalize the textview, button, spinner etc)

Step: -

  1. Go to your Build/gradle
  2. Add this line : - id 'kotlin-android-extensions'
  3. Then Sync the project.

This is Gradle File plugins { id 'com.android.application' id 'kotlin-android' id 'kotlin-android-extensions' }

android { compileSdkVersion 30 buildToolsVersion "30.0.3"

defaultConfig {
    applicationId "com.safal.myapp"
    minSdkVersion 21
    targetSdkVersion 30
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
    jvmTarget = '1.8'
}

}

over 4 years ago · Santiago Trujillo Relatório

0

You can use view.setOnClickListener{ // your task to execute }

Kotlin type inference and automatic lambda expression will handle the boilerplate. Note: Here view can be anything like TextView or button etc.

over 4 years ago · Santiago Trujillo Relatório

0

There are multiple ways to do it, I would prefer kotlin way of doing it and minimise the boilerplate code.

Say you have a Button defined in your layout file like this,

<Button
    android:id="@+id/clickMe"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Ok"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

and you want to add onClickListener to this button clickMe You would need below to do this,

  1. Add kotlin extension to your existing plugins in build.gradle file like below and sync

         plugins {
            id 'kotlin-android-extensions'
        }
    
  2. Add the listener like this,

        clickMe.setOnClickListener {
                Toast.makeText(this@MainActivity, "You clicked me!", Toast.LENGTH_SHORT).show()
            }
    
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda