Click listener android kotlin

How to set OnClickListener for TextView in Kotlin Android

In Android, TextView is a child class of View, and hence can use the method setOnClickListener() on the object of TextView.

In this tutorial, we will learn how to set OnClickListener for TextView in Kotlin file, with the help of an example.

Code – TextView OnClickListener

Following is quick look into code to set OnClickListener for TextView in Kotlin Programming :

// get reference to textview val tv_click_me = findViewById(R.id.tv_click_me) as TextView // set on-click listener tv_click_me.setOnClickListener < // your code to run when the user clicks on the TextView >

Example – OnClickListener for TextView

In this example, we shall look into the layout xml file and Activity(Kotlin file) to set OnClickListener for a TextView.

Create an Android Application with Kotlin Support and replace activity_main.xml and MainActivity.kt with the following content.

activity_main.xml

We have a TextView in LinearLayout. We will use this TextView to set on-click listener.

MainActivity.kt

Get reference to the the TextView in layout file using id, and then call setOnClickListener <> on this TextView. When user clicks on this TextView, the code inside setOnClickListener <> will be executed.

package com.tutorialkart.myapplication import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.TextView import android.widget.Toast class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // get reference to textview val tv_click_me = findViewById(R.id.tv_click_me) as TextView // set on-click listener tv_click_me.setOnClickListener < // your code to perform when the user clicks on the TextView Toast.makeText(this@MainActivity, "You clicked on TextView 'Click Me'.", Toast.LENGTH_SHORT).show() >> >

Following are the screenshots to demonstrate the setOnClickListener for TextView.

MainActivity with TextView

Set OnClickListener for TextView in Kotlin Android - Tutorial - www.tutorialkart.com

Conclusion

In this Kotlin Android Tutorial, we have learnt how to set on-click listener for TextView using TextView.setOnClickListener() method.

Источник

Adding Kotlin OnClickListener to Android views

Just like with Java, you can add a listener to your Android View objects with Kotlin.

To do so, you need to call the setOnClickListener() function from one of your existing View instances.

The View class is the base class used to create all Android UI components like Button and TextView , so you can always call the setOnClickListener() from the UI components added to your XML layout.

For example, here’s how you set the onClickListener to a Button with the id value of button_id :

 In the code block below the setOnClickListener() function call above, you can write any code you want to execute when the button is clicked.

In Java, you might see the setOnClickListener() function call where a new View.OnClickListener instance is created as shown below:

  In Kotlin, the creation of View.OnClickListener and the implementation of the onClick method is done behind the scenes because of Kotlin Java interoperability.

You only need to provide the code to run inside the setOnClickListener call when using Kotlin.

When you have multiple views with click listeners in your view, you might want to separate the implementation of View.OnClickListener from the onCreate() body as follows:

    Alternatively, you can also use a single View.OnClickListener implementation for both views above by checking for the View.id value before executing your code.

Take a look at the example below:

Inside the View.OnClickListener block, you can refer to the View object that’s calling the function using the it keyword.

With the when statement, you can create conditional branches that will run only when the id value of the calling View matches one of the defined values above.

And those are several ways you can implement the OnClickListener interface of the View class using Kotlin.

Unlike in java where everything needs to be explicitly typed, Kotlin has the ability to infer the type of your variables and use a lambda expression as the body of a function call.

You can also separate the implementation of the View.OnClickListener outside of the setOnClickListener() method call.

This allows you to listen to multiple View instances in a concise way.

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Источник

Kotlin Android – Set OnClickListener for Button

Android Button widget is a UI element generally used to receive user actions as input. You can click on a Button, long press, etc.

In this tutorial, we shall learn to set OnClickListener for Button.

Code – Button.setOnClickListener()

Following code helps you to set on-click listener for Button.

// get reference to button val btn_click_me = findViewById(R.id.btn_click_me) as Button // set on-click listener btn_click_me.setOnClickListener

What we have done here is, we got the reference to the Button and then used setOnClickListener method to trigger an action when the button is clicked.

Example – Kotlin Androide Button.setOnClickListener()

Now we shall look into the layout xml file and Activity(Kotlin file) to set OnClickListener for a Button.

Create an Android Application with Kotlin Support and replace activity_main.xml and MainActivity.kt with the following content.

activity_main.xml

MainActivity.kt

package com.tutorialkart.myapplication import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.Toast class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // get reference to button val btn_click_me = findViewById(R.id.btn_click_me) as Button // set on-click listener btn_click_me.setOnClickListener < // your code to perform when the user clicks on the button Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show() >> >

Build and Run the Android Application. You would see the Android screen as shown in the following screenshot.

Set OnClickListener for Button in Kotlin Android - Kotlin Android Tutorial - www.tutorialkart.com

Action performed on clicking the button - Kotlin Android Tutorial - www.tutorialkart.com

Button.setOnClickListener() will be triggered and the code in this setOnClickListener<> block will run.

Conclusion

In this Android Tutorial – Kotlin Button OnclickListener, we have learnt to set OnClickListener for Button in Kotlin Android using Button. setOnClickListener() method.

Источник

Android Button using Kotlin and XML

Android Button using Kotlin and XML

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Android Button Overview

Android Button class extends TextView. Button is a UI widget that is used to get click interactions from the user to trigger an action in the application. A button can be created in the XML layout as well as the Kotlin Activity class in the Android Studio Project.

Creating a Button in XML Layout

  • android:id is used to set the unique identifier on the Button.
  • The android:text is used to set the text inside the button. By default text is displayed in capital letters.
  • android:onClick is used to define the Kotlin function to be invoked in the activity when the button is clicked. It is a click listener.
  • The android:background is used to set the background color/drawable on the Button.

Tip: To prevent displaying all letters in captial, use the attribute android:textAllCaps=»false»

For more details on how to customize your Buttons in XML Layout refer to the Android Buttons Tutorial.

Button Click Listeners

We can set button listeners programmatically too. Following are the two major listeners:

  1. setOnClickListener — triggers when a button is clicked.
  2. setOnLongClickListner — triggers when a button is pressed for a longer duration.

Following code snippets has the setOnClickListener set over a button.

button.setOnClickListener(object : View.OnClickListener < override fun onClick(v: View?) < //your implementation goes here >>) 

The above code can be converted in a lambda expression to make it short.

Similarly, a setOnLongClickListener can be defined in the following manner.

button.setOnLongClickListener < textView.text = "Androidly Button Long click" true >//or button.setOnLongClickListener

In the above code, the last statement in each of the expressions is the return statement.

  • If the setOnLongClickListener returns true, it means that the setOnClickListener won’t be triggered.
  • If the setOnLongClickListener returns false, it means that the setOnClickListener will be triggered.

This is known as consuming events. The first case consumes the event.

Android Button using Kotlin

We’ll be developing an application that increments the counter of the TextView on a Button click. We will use Kotlin to create the button. We’ll also learn about the different Button click handlers.

1. Project Structure

android button project structure

Create a new Android Studio Project. Ensure that in the initial setup, you enable Kotlin Support. Once you’re done, following is the Project Structure that you shall see.

2. Kotlin Button Code

The activity_main.layout file looks like the following code.

android button strings xml

We’ve used LinearLayout that holds the views linearly (horizontally or vertically). It’s recommended to set the strings in the strings.xml file instead of hardcoding them. To fetch a string resource we use @string/name_of_string . The function addOne(view: View) is defined in the MainActivity.kt Kotlin class. The code for the MainActivity.kt class is given below.

package net.androidly.androidlybuttons import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v4.content.ContextCompat import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.LinearLayout import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), View.OnClickListener < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var androidlyButton = Button(this) androidlyButton.apply < layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) text = "Double the value" setAllCaps(false) textSize = 20f >androidlyButton.setOnClickListener(this) linearLayout.addView(androidlyButton) androidlyButton = Button(this) androidlyButton.apply < layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) text = "RESET" textSize = 20f setTextColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimaryDark)) setOnLongClickListener < txtCounter.text = 0.toString() true >> androidlyButton.setOnClickListener(this) linearLayout.addView(androidlyButton) > override fun onClick(v: View?) < when (v?.id) < R.id.btnDouble -> < txtCounter.text = (txtCounter.text.toString().toInt() * 2).toString() >R.id.btnReset -> < txtCounter.text = (-100).toString() >else -> < >> > fun addOne(view: View) < txtCounter.text = (txtCounter.text.toString().toInt() + 1).toString() >> 
  1. import kotlinx.android.synthetic.main.activity_main.* statement automatically gets the view IDs from the xml in our class. Hence saving us from using findViewById.
  2. The fun addOne(view: View) is triggered when the btnIncrementByOne is clicked. The (view: View) parameter must be defined in the function declaration.
  3. Create a Button programmatically and set it in the parent view(LinearLayout here) using the following code.

var androidlyButton = Button(this) linearLayout.addView(androidlyButton) 

android button ids

  • Instead of calling member functions on the Button class, we can use apply<> lambda expression.
  • The layoutParams is used to define the width and height of the button. The MATCH_PARENT sets the width/height equal to the linear layout. WRAP_CONTENT wraps the view to the size of the content.
  • We can set the id programmatically under res | values | ids.xml.
  • We’ve defined the View.OnClickListener interface in our MainActivity.kt class. Hence we need to override its onClick() function.
  • Inside the onClick function, we use the Kotlin when statement, which is equivalent to switch in other languages.
  • For the onClick function to be triggered, you must register the setOnClickListener over the button with the interface using the context( this ).
  • Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Источник

    Читайте также:  Что такое тензор питон
    Оцените статью