Kotlin 및 XML을 사용하는 Android 버튼
이 튜토리얼에서는 Kotlin 프로그래밍을 사용하여 Android 앱에서 버튼을 만드는 방법을 배웁니다.
Android 버튼 개요
Android Button 클래스는 TextView를 확장합니다. 버튼은 애플리케이션에서 작업을 트리거하기 위해 사용자의 클릭 상호 작용을 가져오는 데 사용되는 UI 위젯입니다. Android Studio 프로젝트의 Kotlin Activity 클래스뿐만 아니라 XML 레이아웃에서도 버튼을 만들 수 있습니다.
XML 레이아웃에서 버튼 만들기
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Androidly Button"/>
- android:id는 버튼의 고유 식별자를 설정하는 데 사용됩니다.
android:text
는 버튼 안에 텍스트를 설정하는 데 사용됩니다. 기본적으로 텍스트는 대문자로 표시됩니다.android:onClick
은 버튼을 클릭할 때 활동에서 호출할 Kotlin 함수를 정의하는 데 사용됩니다. 클릭 리스너입니다.android:background
는 Button의 배경색/드로어블을 설정하는 데 사용됩니다.
도움말: 모든 문자를 대문자로 표시하지 않으려면 android:textAllCaps=\false\
속성을 사용하세요.
XML 레이아웃에서 버튼을 맞춤설정하는 방법에 대한 자세한 내용은 Android 버튼 자습서를 참조하세요.
버튼 클릭 리스너
프로그래밍 방식으로 버튼 리스너를 설정할 수도 있습니다. 다음은 두 가지 주요 청취자입니다.
setOnClickListener
- 버튼을 클릭하면 트리거됩니다.setOnLongClickListner
- 버튼을 더 오래 누르면 트리거됩니다.
다음 코드 스니펫에는 버튼 위에 설정된 setOnClickListener가 있습니다.
button.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
//your implementation goes here
}
})
위의 코드는 람다 식으로 변환하여 짧게 만들 수 있습니다.
button.setOnClickListener {
textView.text = "Androidly Buttons"
}
마찬가지로 setOnLongClickListener는 다음과 같은 방식으로 정의할 수 있습니다.
button.setOnLongClickListener {
textView.text = "Androidly Button Long click"
true
}
//or
button.setOnLongClickListener {
textView.text = "Androidly Button Long click"
false
}
위의 코드에서 각 식의 마지막 문은 return 문입니다.
- setOnLongClickListener가 true를 반환하면 setOnClickListener가 트리거되지 않는다는 의미입니다.
- setOnLongClickListener가 false를 반환하면 setOnClickListener가 트리거됨을 의미합니다.
이를 소비 이벤트라고 합니다. 첫 번째 사례는 이벤트를 소비합니다.
Kotlin을 사용하는 Android 버튼
Button 클릭 시 TextView의 카운터를 증가시키는 애플리케이션을 개발할 것입니다. Kotlin을 사용하여 버튼을 만듭니다. 또한 다양한 버튼 클릭 핸들러에 대해서도 알아봅니다.
1. 프로젝트 구조

2. 코틀린 버튼 코드
activity_main.layout 파일은 다음 코드와 같습니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/txtCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/number_zero"
android:textAppearance="@style/TextAppearance.AppCompat.Display2"
android:textColor="#000" />
<Button
android:id="@+id/btnIncrementByOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addOne"
android:text="@string/increment_by_one" />
</LinearLayout>

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
id = R.id.btnDouble
}
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))
id = R.id.btnReset
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()
}
}
중요 사항:


프로젝트 다운로드: AndroidlyButtons