[英]single material Toggle button with image
我在我的应用程序中使用了 Google Material design library,并且很惊讶它没有 Toggle 按钮。 有切换按钮组,但是如果我需要一个按钮来打开和关闭,我该怎么办。 我的用例是打开时显示一张图像,关闭时显示另一张图像。 我试图用开关来做到这一点,但必须进行大量复杂的定制。 有什么办法可以使用简单的材质按钮作为切换按钮吗?
您可以使用以下内容:
<com.google.android.material.button.MaterialButton
android:id="@+id/toogleButtton"
style="@style/ToggleButton"
android:checkable="true"
android:layout_width="48dp"
android:layout_height="48dp"
app:icon="@drawable/ic_add_24px"/>
和
toogleButtton.setIcon(createHeaderToggleDrawable(this))
toogleButtton.isChecked = true
// Create StateListDrawable programmatically
private fun createHeaderToggleDrawable(context: Context): Drawable {
val toggleDrawable = StateListDrawable()
toggleDrawable.addState(
intArrayOf(android.R.attr.state_checked),
AppCompatResources.getDrawable(context, R.drawable.xxx)
)
toggleDrawable.addState(
intArrayOf(),
AppCompatResources.getDrawable(context, R.drawable.xxxx)
)
return toggleDrawable
}
在样式中自定义颜色:
<style name="ToggleButton" parent="Widget.MaterialComponents.Button.TextButton">
<item name="iconTint">?attr/colorPrimary</item>
<item name="android:insetTop">0dp</item>
<item name="android:insetBottom">0dp</item>
<item name="android:padding">12dp</item>
<item name="rippleColor">@color/mtrl_btn_ripple_color</item>
</style>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.