androidandroid-jetpack-composeandroid-togglebutton

how to design jetpack compose toggle buttons for week days


I have design below toggle buttons in xml

xml UI screenshot

Toggle button

<androidx.appcompat.widget.AppCompatToggleButton
    android:id="@+id/tb_sun"
    style="@style/ToggleButton"
    android:layout_width="@dimen/dp_36"
    android:layout_height="@dimen/dp_36"
    android:layout_marginEnd="@dimen/dp_3"
    android:background="@drawable/toggle_bg"
    android:textOff="S"
    android:textOn="S" />
    
    
toggle_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/shape_oval_outline" android:state_checked="false" />
    <item android:drawable="@drawable/shape_oval" android:state_checked="true" />
</selector>

shape_oval_outline.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <stroke
        android:width="1dp"
        android:color="@color/colorAccent" />
</shape>

shape_oval.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/colorAccent" />
</shape>

Now I need to design this in jetpack compose. I tried with IconButton, but can't use shape drawable there. How can design this in jetpack compose?

@Composable
fun ToggleButtonCompose() {
    IconButton(
        onClick = {},
        enabled = true,
        content = {
            Icon(
                painter = painterResource(id = R.drawable.shape_oval),
                contentDescription = ""
            )
        }
    )
}

Solution

  • You can use the IconToggleButton without using drawable resources.
    Just use the clip and border modifier to achieve the shape:

    var checked by remember { mutableStateOf(false) }
    
    val tint by animateColorAsState(if (checked) Teal200 else Black)
    val textColor = if (checked) White else Teal200
    
    IconToggleButton(
        checked = checked,
        onCheckedChange = { checked = it },
        modifier = Modifier
            .clip(CircleShape)
            .border(1.dp, Teal200, CircleShape)
            .background(tint)
    
    ) {
         Text("M", color = textColor)
    }
    

    enter image description here