Home > Net >  How to create a selector for a Button programmatically
How to create a selector for a Button programmatically

Time:07-08

How to create a selector programmatically (Kotlin) for an ImageButton with the following requirements.

  • Only the background scales by 25% while the image remains the same size while the button is at the Pressed state.
  • The background colour of the button at the Pressed state is different from that of the normal (default) state.
  • able to set the background colour programmatically for the button so that the same button can be reused.

Thank you for all the help in advance

CodePudding user response:

You will need to recreate the following drawable programmatically:

<selector>
    <item android:drawable="@android:color/holo_blue_light" android:state_pressed="true" />
    <item>
        <inset android:drawable="@android:color/holo_red_light" android:inset="12.5%" />
    </item>
</selector>

This enter image description here

The green square is there just to show the true extent of the ImageButton.

Here is the code to create the StateListDrawable programmatically and to assign it to the ImageButton:

val blue = ContextCompat.getColor(requireContext(), android.R.color.holo_blue_light)  
val red = ContextCompat.getColor(requireContext(), android.R.color.holo_red_light)  
  
// Create the inset drawable that is inset 12.5% on each side. This will be the default state.  
val colorDrawable = ColorDrawable(red)  
val insetDrawable = InsetDrawable(colorDrawable, 0.12f)  
  
// Create the drawable that will be the pressed state background.  
val pressedStateDrawable = ColorDrawable(blue)  
val bg = StateListDrawable()  
bg.addState(intArrayOf(android.R.attr.state_pressed), pressedStateDrawable)  
bg.addState(intArrayOf(), insetDrawable)  
binding.imageButton.background = bg


If you want to animate the background, you can use a enter image description here

CodePudding user response:

try it in your xml code

android:foreground="?selectableItemBackground"
  • Related