CardView's background which will respond to android:state_selected and android:state_pressed

后端 未结 5 1581
独厮守ぢ
独厮守ぢ 2020-12-11 12:33

I\'m referring to the answer at https://stackoverflow.com/a/24475228/72437

The proposed answer is using drawable from Android : ?android:attr/selectableItemBac

5条回答
  •  一向
    一向 (楼主)
    2020-12-11 12:57

    I've just tried MaterialCardView and this works:

    
    

    selector_background_color.xml

    
    
    
    
    

    In the Activity/Fragment:

    material_card_view.setOnClickListener {
            it.isActivated = !it.isActivated
    }
    

    For the strokeColor though, you can't use a selector. You will have to do it programmatically if you want the stroke color to change as per selector state.

    Example for state_activated:

    val colorStateList: ColorStateList = 
    ResourcesCompat.getColorStateList(resources, 
    R.color.selector_stroke_color, null)!!
    val colorForState =colorStateList.getColorForState(intArrayOf(android.R.attr.state_activated), colorStateList.defaultColor)
    material_card_view.strokeColor = colorForState
    

提交回复
热议问题