我想在一个普通按钮的中心有一个图标,使用 anko。我试过
button.backgroundResource = R.drawable.arrow_forward
但是我可以绘制覆盖整个按钮并从其父级获取背景颜色(在按钮上设置背景颜色没有任何作用)。
我也试过 drawable = ...
了,效果一样。如何设置带有 anko 的图标以具有原始纵横比并居中?
首先,为了在按钮上设置图标/图像,您应该使用ImageButton
.
然后很容易。
imageButton{
imageResource = R.drawable.ic_cc_checkmark
}
如果您需要使用其他资源或可绘制对象,则在不获取资源未找到错误的情况下获取它使用ctx.getDrawable(R.x.y)
希望这可以帮助某人
不确定 Anko 应该如何工作。从技术上讲,对于 android,假设您有一个图像按钮,您应该这样做:
((ImageButton)findViewById(R.id.yourButtonID)).setImageResource(R.drawable.yourDrawable);
如果其他人仍在努力实现这一目标,这里有一个指南:
1. 创建一个扩展函数(可能在一个独立.kt
文件中,或者在Activity
您Fragment
想要使用按钮的类文件中),如下所示:
inline fun ViewManager.materialButton(@StyleRes theme: Int, init: MaterialButton.() -> Unit = {}): MaterialButton {
return ankoView({ MaterialButton(it) }, theme, init = init)
}
materialButton(R.style.App_ThemeOverlay /** some overlay theme **/) {
icon = context.getDrawable(R.drawable.arrow_forward)
// ... other regular and material button properties here ...
}