1

我想在一个普通按钮的中心有一个图标,使用 anko。我试过

button.backgroundResource = R.drawable.arrow_forward

但是我可以绘制覆盖整个按钮并从其父级获取背景颜色(在按钮上设置背景颜色没有任何作用)。

在此处输入图像描述

我也试过 drawable = ...了,效果一样。如何设置带有 anko 的图标以具有原始纵横比并居中?

4

3 回答 3

4

首先,为了在按钮上设置图标/图像,您应该使用ImageButton.

然后很容易。

imageButton{
     imageResource = R.drawable.ic_cc_checkmark
}

如果您需要使用其他资源或可绘制对象,则在不获取资源未找到错误的情况下获取它使用ctx.getDrawable(R.x.y)

希望这可以帮助某人

于 2017-04-16T18:13:39.127 回答
1

不确定 Anko 应该如何工作。从技术上讲,对于 android,假设您有一个图像按钮,您应该这样做:

((ImageButton)findViewById(R.id.yourButtonID)).setImageResource(R.drawable.yourDrawable);
于 2017-04-14T13:34:43.360 回答
1

如果其他人仍在努力实现这一目标,这里有一个指南:

1. 创建一个扩展函数(可能在一个独立.kt文件中,或者在ActivityFragment想要使用按钮的类文件中),如下所示:

inline fun ViewManager.materialButton(@StyleRes theme: Int, init: MaterialButton.() -> Unit = {}): MaterialButton {
    return ankoView({ MaterialButton(it) }, theme, init = init)
}
  1. 然后像其他 Anko 视图一样使用您的按钮,如下所示:
materialButton(R.style.App_ThemeOverlay /** some overlay theme **/) {
  icon = context.getDrawable(R.drawable.arrow_forward)
  // ... other regular and material button properties here ...
}
于 2020-05-01T00:24:25.490 回答