LoginSignup
7
8

More than 5 years have passed since last update.

[Android]KotlinでCustomViewを作るときのメモ

Posted at

はじめに

KotlinでCustomViewを作るときのメモ。
作り方は、3種類あります。

No.1 セカンダリコンストラクタで全部書く

CustomView1.kt
class CustomView1 : LinearLayout {

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
        LayoutInflater.from(context).inflate(R.layout.input_item_view, this, true)
    }

}

No.2 プライマリコンストラクタに@JvmOverloads

CustomView2.kt
class CustomView2 @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyle: Int = 0
) : LinearLayout(context, attrs, defStyle) {

    init {
        LayoutInflater.from(context).inflate(R.layout.input_item_view, this, true)
    }

}

No.3 セカンダリコンストラクタに@JvmOverloads

CustomView3.kt
class CustomView3 : LinearLayout {
    @JvmOverloads
    constructor(
            context: Context,
            attrs: AttributeSet? = null,
            defStyle: Int = 0
    ) : super(context, attrs, defStyle)

    init {
        LayoutInflater.from(context).inflate(R.layout.input_item_view, this)
    }
}
7
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8