Kotlin Android Button — это кнопка, используемая для выполнения событий и обработки при ее нажатии. Это компонент пользовательского интерфейса, относящийся к классу android.widget.Button. Чтобы узнать больше о кнопке Android, обратитесь к примеру кнопки Android.
Используя Котлин, мы можем выполнять события на кнопке Android разными способами:
1. Реализация setOnClickListener кнопки
button1.setOnClickListener(){
Toast.makeText(this,"button 1 clicked", Toast.LENGTH_SHORT).show()
}
2. Реализация View.OnClickListner и переопределение его функции.
button2.setOnClickListener(this)
. .
override fun onClick(view: View) {
// TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
3. Добавление атрибута onClick кнопки в файл макета и реализация его функции.
fun clickButton(v: View){
val mToast = Toast.makeText(applicationContext,"button 3 clicked", Toast.LENGTH_SHORT)
mToast.show()
}
4. Программное создание кнопки и установка ее на макете.
button4.setLayoutParams(ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT))
button4.setId(button4_Id)
button4.x = 250f
button4.y = 500f
button4.setOnClickListener(this)
constraintLayout.addView(button4)
Пример Kotlin Android Button
В этом примере мы создадим кнопку и выполним для нее событие. Нажав на кнопку, отобразится всплывающее сообщение.
Activity_main.xml
Добавьте три кнопки из палитры виджетов в файл макета activity_main.xml. Его код приведен ниже. Кнопка с идентификатором button3 добавила атрибут onClick, а имя ее функции реализовано в файле класса MainActivity.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/constraintLayout"
tools:context="example.javatpoint.com.kotlinbutton.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Action Example"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.073"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>
<Button
android:id="@+id/button1"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Button 1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.498" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="80dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Button 2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.762" />
<Button
android:id="@+id/button3"
android:layout_width="101dp"
android:layout_height="48dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:onClick="clickButton"
android:text="Button 3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.774" />
</android.support.constraint.ConstraintLayout>
MainActivity.kt
Добавьте следующий код в класс MainActivity.kt. В этом классе мы реализуем прослушиватель setOnClickListener для кнопки, реализуем OnClickListener класса View(View.OnClickListener) и переопределяем его функцию onClick. В этом классе мы также программно создаем кнопку(button4), определяем ее свойства и устанавливаем на макете.
package example.javatpoint.com.kotlinbutton
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() , View.OnClickListener {
val button4_Id: Int = 1111
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button1.setOnClickListener(){
Toast.makeText(this,"button 1 clicked", Toast.LENGTH_SHORT).show()
}
button2.setOnClickListener(this)
// add button dynamically
val button4 = Button(this)
button4.setText("Button 4 added dynamically")
button4.setLayoutParams(ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT))
button4.setId(button4_Id)
button4.x = 250f
button4.y = 500f
button4.setOnClickListener(this)
constraintLayout.addView(button4)
}
override fun onClick(view: View) {
// TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
when(view.id) {
R.id.button2 ->
Toast.makeText(this,"button 2 clicked", Toast.LENGTH_SHORT).show()//single line code
button4_Id->{//multiline code
val myToast = Toast.makeText(this,"button 4 clicked", Toast.LENGTH_SHORT)
myToast.show()
}
}
}
fun clickButton(v: View){
val mToast = Toast.makeText(applicationContext,"button 3 clicked", Toast.LENGTH_SHORT)
mToast.show()
}
}
Вывод:



