複数の画面で共通したデザインや処理を持つボタンを使用するとき、カスタムボタンを作成すると便利です。
カスタムボタンクラスを作成する方法をメモします。
AppCompatButton を継承した CustomButton クラスを作成します。
class CustomButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.buttonStyle
) : AppCompatButton(context, attrs, defStyleAttr) {
init {
// 初期設定
}
}
作成したCustomButtonは、通常のボタンと同じようにXMLから使用できます。
<com.example.CustomButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ボタン" />
CustomButtonでできること
通常のボタンにはない共通処理や設定をまとめることができます。CustomButtonでできることを3つメモします。
1 ボタンの見た目を共通化する
アプリ内のボタンをすべて角丸にします。角丸や文字色などの共通設定を適用でき、画面ごとに同じ設定を書く必要がなくなるため、デザインを統一しやすくなります。
class CustomButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.buttonStyle
) : AppCompatButton(context, attrs, defStyleAttr) {
init {
background = GradientDrawable().apply {
cornerRadius = 16f
setColor(Color.BLUE)
}
setTextColor(Color.WHITE)
}
}
2 ボタンの状態に応じて見た目を変更する
ボタンの有効・無効時の見た目を変更します。以下コードは通常のButtonと同じように、customButton.isEnabled = falseとするだけで、CustomButton側で見た目を変更できます。これで「入力内容が不足している場合はボタンを無効にする」といった処理を共通化できます。
class CustomButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.buttonStyle
) : AppCompatButton(context, attrs, defStyleAttr) {
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
alpha = if (enabled) {
1.0f
} else {
0.5f
}
}
}
3 クリック処理などの重複防止処理を追加する
ボタンをクリックしたときに二重クリックを防止する処理を追加できます。
以下コードは1秒以内に連続してクリックされた場合に2回目以降のクリックを無視します。画面側では通常のButtonと同じように使用できます。
class CustomButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.buttonStyle
) : AppCompatButton(context, attrs, defStyleAttr) {
private var lastClickTime = 0L
override fun performClick(): Boolean {
val currentTime = System.currentTimeMillis()
if (currentTime - lastClickTime < 1_000L) {
return true
}
lastClickTime = currentTime
return super.performClick()
}
}
customButton.setOnClickListener {
// ボタンがクリックされたときの処理
}