using a custom color for button background while using selectableItemBackground attribute

后端 未结 6 2304
伪装坚强ぢ
伪装坚强ぢ 2021-02-06 21:37

I am trying to use

android:background=\"?android:attr/selectableItemBackground\"

to get my button to do appropriate effects for each android versi

6条回答
  •  半阙折子戏
    2021-02-06 22:12

    if you want to do it programmatically:

    fun setSelectableBgWithColor(view: View, bgColor: Int? = null) {
        val bgSelectable = getDrawableResCompat(view.context, android.R.attr.selectableItemBackground)
        val bg = if (bgColor == null) bgSelectable else LayerDrawable(
            arrayOf(ColorDrawable(color), bgSelectable)
        )
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.background = bg
        } else {
            view.setBackgroundDrawable(bg)
        }
    }
    
    fun getDrawableResCompat(context: Context, @AttrRes id: Int): Drawable? {
        return TypedValue()
            .also { context.theme.resolveAttribute(id, it, true) }
            .let {
                val resId = if (it.resourceId != 0) it.resourceId else it.data
                ContextCompat.getDrawable(context, resId)
            }
    }
    

提交回复
热议问题