0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Androidで共通設定のカスタムViewを作成する

0
Posted at

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
    }
}

レイアウト側の設定がスッキリして実装のブレを防ぐことにつながります。同じ実装が多い場合は積極的に実装していきたいです。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?