iconSwitch Library in Android

Full source code by using an awesome library called iconSwitch with which we can create custom toggle switches that show icons on the left and right side. We can change it’s attributes like color, size, icons and we will implement an onCheckedChangeListener to react to toggles on that switchv

Gradle

implementation 'com.polyak:icon-switch:1.0.0'

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="tech.codingpoint.iconswitchexample.MainActivity">

    <com.polyak.iconswitch.IconSwitch
        android:id="@+id/icon_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        app:isw_default_selection="right"
        app:isw_icon_left="@drawable/ic_list"
        app:isw_icon_right="@drawable/ic_location"
        app:isw_icon_size="25dp" />

</RelativeLayout>

MainActivity.java

package tech.codingpoint.iconswitchexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.polyak.iconswitch.IconSwitch;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IconSwitch iconSwitch = findViewById(R.id.icon_switch);
        iconSwitch.setCheckedChangeListener(new IconSwitch.CheckedChangeListener() {
            @Override
            public void onCheckChanged(IconSwitch.Checked current) {
                switch (current) {
                    case LEFT:
                        Toast.makeText(MainActivity.this, "Left", Toast.LENGTH_SHORT).show();
                        break;
                    case RIGHT:
                        Toast.makeText(MainActivity.this, "Right", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }
}

Leave a Comment