Issue
What would be the best way to build a togglebutton in android like shown in the image below. I spend more time than i like to admit trying to get it right but so far it seems inpossible to get rounded background and an icon at the same time.
My Layout
<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"
Check
<?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>
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>
What i got
Solution
You can use a MaterialButton
with 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"
../>
where btn_toggle_background
is a selector
<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>
with:
button.addOnCheckedChangeListener { button, isChecked ->
if (isChecked){
button.icon = ContextCompat.getDrawable(this,R.drawable.xxx)
} else {
button.icon = ContextCompat.getDrawable(this,R.drawable.xxx)
}
}
Answered By - Gabriele Mariotti
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.