Android 如何创建带有图标和文本的切换按钮
在android中构建切换按钮的最佳方法是什么,如下图所示。我花的时间比我愿意承认的要多,但到目前为止,似乎不可能同时获得圆形背景和图标 我的布局Android 如何创建带有图标和文本的切换按钮,android,android-layout,android-button,material-components-android,Android,Android Layout,Android Button,Material Components Android,在android中构建切换按钮的最佳方法是什么,如下图所示。我花的时间比我愿意承认的要多,但到目前为止,似乎不可能同时获得圆形背景和图标 我的布局 <ToggleButton android:id="@+id/addButton" android:layout_width="match_parent" android:layout_height="
<ToggleButton
android:id="@+id/addButton"
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="@drawable/button_bg_rounded_corners"
android:button="@drawable/check"
您可以将MaterialButton
与android:checkable=“true”
一起使用:
与:
我建议您使用com.google.android.material.button.MaterialButton
。它具有以下属性:app:icon
,app:iconGravity
,app:iconSize
,app:iconTint
,app:backgroundTint
。通过这些,您可以实现如图片所示的UI。是的,它实际上不是ToggleButton
,但对我来说,在ViewModel
或Fragment
中本地跟踪toggled
状态要比为背景创建适当的xml更容易。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/app_checkmark"
android:state_checked="true" />
<item android:drawable="@drawable/app_close"
android:state_checked="false"/>
</selector>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape android:shape="rectangle" >
<solid android:color="@color/appcolor_yellow" />
<corners android:radius="20dp" />
</shape>
</item>
<item android:state_checked="false" >
<shape android:shape="rectangle" >
<solid android:color="@color/appcolor_green"/>
<corners android:radius="20dp" />
</shape>
</item>
</selector>
<com.google.android.material.button.MaterialButton
android:checkable="true"
app:backgroundTint="@drawable/btn_toggle_background"
app:iconGravity="start"
app:icon="@drawable/..."
app:cornerRadius="20dp"
../>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:color="@color/..." />
<item android:state_checked="true" android:color="@color/..." />
</selector>
button.addOnCheckedChangeListener { button, isChecked ->
if (isChecked){
button.icon = ContextCompat.getDrawable(this,R.drawable.xxx)
} else {
button.icon = ContextCompat.getDrawable(this,R.drawable.xxx)
}
}