Androidでレイアウトを作成してるときに
android:clickable="true"
android:focusable="true"
を毎回ルートに毎回書いています。カスタムレイアウトを作成すればそれらをまとめて設定できます。
class CustomLinearLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
init {
isClickable = true
isFocusable = true
}
}
<com.example.ClickableLinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- 子View -->
</com.example.ClickableLinearLayout>
もし画面の設定が決まっている場合、以下のようにRipple・アクセシビリティなどを最初から組み込みます。
class CCustomLinearLayout2 @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
init {
isClickable = true
isFocusable = true
isFocusableInTouchMode = true
// アクセシビリティ
importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_YES
// Ripple
if (foreground == null) {
val typedValue = TypedValue()
context.theme.resolveAttribute(
android.R.attr.selectableItemBackground,
typedValue,
true
)
foreground = ContextCompat.getDrawable(context, typedValue.resourceId)
}
isDuplicateParentStateEnabled = false
isSoundEffectsEnabled = true
}
}
レイアウト側の設定がスッキリして実装のブレを防ぐことにつながります。同じ実装が多い場合は積極的に実装していきたいです。