Ste*_*n.B 3 android android-layout android-button material-components-android
在 android 中构建切换按钮的最佳方法是什么,如下图所示。我花费的时间比我愿意承认的要多,但到目前为止,似乎不可能同时获得圆形背景和图标。
我的布局
<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"
Run Code Online (Sandbox Code Playgroud)
查看
<?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>
Run Code Online (Sandbox Code Playgroud)
BG
<?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>
Run Code Online (Sandbox Code Playgroud)
我得到了什么
您可以使用MaterialButtonwith android:checkable="true":
<com.google.android.material.button.MaterialButton
android:checkable="true"
app:backgroundTint="@drawable/btn_toggle_background"
app:iconGravity="start"
app:icon="@drawable/..."
app:cornerRadius="20dp"
../>
Run Code Online (Sandbox Code Playgroud)
btn_toggle_background选择器在哪里
<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>
Run Code Online (Sandbox Code Playgroud)
和:
button.addOnCheckedChangeListener { button, isChecked ->
if (isChecked){
button.icon = ContextCompat.getDrawable(this,R.drawable.xxx)
} else {
button.icon = ContextCompat.getDrawable(this,R.drawable.xxx)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3764 次 |
| 最近记录: |