Slide to Unlock Demo in Android

By | June 25, 2017

This is a simple demo to do Slide to Unlock in Android.

Layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    tools:context="slide_unlock.coderzheaven.com.slidetounlockdemo.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:gravity="center"
        android:text="Slide to unlock"
        android:textStyle="bold" />

    <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:max="100"
        android:progress="0"
        android:progressDrawable="@android:color/transparent"
        android:thumb="@drawable/hand" />

</RelativeLayout>

Activity

package slide_unlock.coderzheaven.com.slidetounlockdemo;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.SeekBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        SeekBar mSeekbar = (SeekBar) findViewById(R.id.seekbar);
        mSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int alpha = (progress * (255 / 100));
                seekBar.getThumb().setAlpha(255 - alpha);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

                if (seekBar.getProgress() < 90) {
                    seekBar.setThumb(ContextCompat.getDrawable(MainActivity.this, R.drawable.hand));
                    seekBar.setProgress(0);
                } else {
                    seekBar.setProgress(100);
                    seekBar.getThumb().setAlpha(0);
                    Toast.makeText(MainActivity.this, "Unlocked", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *