android - 单一材质 带图像的切换按钮
问题描述
我在我的应用程序中使用 Google Material 设计库,并且很惊讶它没有切换按钮。有切换按钮组,但如果我需要一个按钮来打开和关闭,我该怎么办。我的用例是打开时显示一张图像,关闭时显示另一张图像。我试图用开关来做,但必须进行很多复杂的定制。有什么方法可以使用简单的材质按钮作为切换按钮?
解决方案
你可以使用类似的东西:
<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>
推荐阅读
- python - 将文本文件转换为元组列表
- javascript - 为什么我在这个内存块 javascript 项目中的悬停状态不起作用?
- ios - 在 iOS 13 之前的设备上为单元格返回了意外的高度
- eventstoredb - 如何将特定事件的元数据发布到 EventStore?
- docker - Docker 在卷上安装多个服务
- vue.js - 如何从 VuetifyJS 组合框中获取文本值?
- c# - 睡眠与。延迟与计时器。如何选择最佳选项
- oracle - 用于创建物化视图的 Oracle DDL 错误 PLS-00103
- python - 如何用二进制数组训练多个矩阵
- c++ - Clang 是否正确拒绝仅通过特化定义类模板的嵌套类的代码?