androidkotlinanko

How do I set up an icon (drawable) for a button in anko?


I want to have an icon in the centre of a plain button, using anko. I tried

button.backgroundResource = R.drawable.arrow_forward

but I got drawable covering whole button and getting background colour from its parent (setting background colour on button explicite does nothing).

enter image description here

I tried drawable = ... as well, with same effect. How do I set up an icon with anko to have original aspect ratio and be centered?


Solution

  • If anyone else is still trying to achieve this, here's a guide:

    1. Create an extension function (perhaps in a standalone .kt file or in your Activity or Fragment class file where you want to use the button) like so:

    inline fun ViewManager.materialButton(@StyleRes theme: Int, init: MaterialButton.() -> Unit = {}): MaterialButton {
        return ankoView({ MaterialButton(it) }, theme, init = init)
    }
    
    1. Then use your button like other Anko views, like so:
    materialButton(R.style.App_ThemeOverlay /** some overlay theme **/) {
      icon = context.getDrawable(R.drawable.arrow_forward)
      // ... other regular and material button properties here ...
    }