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