androidstylescustomizationtogglebuttonandroid-togglebutton

How to customize toggle button in android?


I've been trying to customize a toggle button to look like this, but it seems like i'm not getting anywhere.

enter image description here

Can anyone give me an idea or any kind of tutorial on designing?


Solution

  • Is that what you're looking for :

    enter image description here

    First create a ToggleButton XML :

    <ToggleButton
        android:id="@+id/follow"
        android:layout_width="120dp"
        android:layout_height="35dp"
        android:layout_centerInParent="true"
        android:background="#61849f"
        android:checked="false"
        android:drawableStart="@drawable/ic_baseline_star_24"
        android:elevation="0dp"
        android:gravity="center"
        android:padding="8dp"
        android:textColor="#fff"
        android:textOff=" FOLLOW "
        android:textOn=" FOLLOWING " />
    

    Java :

    toggleButton = findViewById(R.id.follow);
            toggleButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) setUnfollow();
                else setFollow();
            });
    

    The setFollow & setUnfollow methods :

    private void setUnfollow() {
        toggleButton.setChecked(true);
        toggleButton.setTextColor(Color.BLACK);
        toggleButton.setBackgroundColor(Color.WHITE);
        toggleButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.border));
    
    }
    
    private void setFollow() {
        toggleButton.setChecked(false);
        toggleButton.setTextColor(Color.WHITE);
        toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.fill));
        toggleButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_baseline_star_24, 0, 0, 0);
    }
    

    Finally The fill.XML and bordre.XML (create these file in the drawable folder)

    Border.XML :

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

    Fill.XML

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