커스텀 뷰를 생성하고, 그 안에서 뷰를 컨트롤하려면 좀 더 간단한 방법이 있다.
자바로 먼저 만들고 나서 코틀린으로 변환하는 것보다 바로 코틀린으로 만드는 게 훨씬 짧다.
게다가 어차피 constructor 에서는 하는 건 아무 것도 없고, init에 context 만 넘기고 있으니 필요없는 코드들을 굳이 볼 필요도 없어졌다.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/nameLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:text="이름"/> <Button android:id="@+id/sendButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="클릭"/> </LinearLayout>
자바로 먼저 만들고 코틀린으로 변환하면 이렇게 나온다.
import kotlinx.android.synthetic.main.view_main.view.* class MainView : LinearLayout { constructor(context: Context) : super(context) { init(context) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init(context) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(context) } private fun init(context: Context) { LayoutInflater.from(context).inflater.inflate(R.layout.view_main, this, true) sendButton.setOnClickListener ({ nameLabel.text = "클릭:" + System.currentTimeMillis() }) } }
코틀린으로 만들면 이렇게 된다.
import kotlinx.android.synthetic.main.view_main.view.* class MainView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { init { LayoutInflater.from(context).inflate(R.layout.view_main, this, true) sendButton.setOnClickListener ({ nameLabel.text = "클릭: " + System.currentTimeMillis() }) } }
출처: https://antonioleiva.com/kotlin-android-extensions/