改写控件之《仿iOS滑动枷锁样式的登录》

转载请注明出处:王亟亟的大牛之路

iOS的滑动解锁你的心系列(张翰梗)一直是个人觉得蛮好的看的一个东西,然后今天就把这样的一个控件应用到我们今天的Demo中让他滑动解锁。

样式是这样的:出处

初始化

滑好后

包目录:



流程–用户打开App–输入账号密码–滑动登录–正确/错误–登陆成功提示/弹出对话框。

很普遍的登陆流程,只是在具体实现上做一些改变,摆脱单一的登录,注册按钮等。

MainActivity:

public class MainActivity extends AppCompatActivity implements SlideBar.OnTriggerListener,OnTouchListener{
    SlideBar slideToUnLock;
    IconEditText users,password;
    String User,Password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        slideToUnLock = (SlideBar)findViewById(R.id.slideBar);
        users=(IconEditText)findViewById(R.id.user);
        password=(IconEditText)findViewById(R.id.password);

        slideToUnLock.setOnTouchListener(this);
        slideToUnLock.setOnTriggerListener(this);
    }

    @Override
    public void onTrigger() {
        Toast.makeText(this, getResources().
                getString(R.string.unlock_string), Toast.LENGTH_SHORT).show();
    }

    void logic(){
        User=users.getEditText().getText().toString();
        Password=password.getEditText().getText().toString();
        if(!User.equals("wjj")||!Password.equals("123")){
            dialog();
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action=event.getAction();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                logic();
                break;
        }
        return false;
    }

    public void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
         builder.setMessage("? ??? ????");
         builder.setTitle("?? ??");
         builder.setPositiveButton("???.", new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
                 dialog.dismiss();
             }
         });
         builder.create().show();
         }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

主布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:widget="http://schemas.android.com/apk/res-auto"
    xmlns:prvandroid="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="@drawable/bg">

        <RelativeLayout
            android:layout_marginLeft="40dp"
            android:layout_marginRight="40dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true">

            <logdemo.wjj.com.logdemo.Custom.IconEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColorHint="#ffffff"
                widget:hint="@string/user_name"
                widget:iconSrc="@mipmap/users"
                android:id="@+id/user"
                widget:isPassword="false"
                android:background="@drawable/layout_bg">
            </logdemo.wjj.com.logdemo.Custom.IconEditText>

            <logdemo.wjj.com.logdemo.Custom.IconEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColorHint="#ffffff"
                widget:hint="@string/password"
                widget:iconSrc="@mipmap/lock"
                android:id="@+id/password"
                widget:isPassword="true"
                android:layout_below="@id/user"
                android:layout_marginTop="30dp"
                android:background="@drawable/layout_bg">
            </logdemo.wjj.com.logdemo.Custom.IconEditText>
        </RelativeLayout>
    <logdemo.wjj.com.logdemo.Custom.SlideBar
        android:id="@+id/slideBar"
        android:layout_width="@dimen/slide_bar_width"
        android:layout_height="@dimen/slide_bar_height"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dip"
        android:background="@drawable/layout_bg"
        prvandroid:MinVelocityXToUnlock="1500"
        prvandroid:MinDistanceToUnlock="240"
        prvandroid:LeftAnimationDuratioin="200"
        prvandroid:RightAnimationDuratioin="300">
        <logdemo.wjj.com.logdemo.Custom.GradientView
            android:id="@+id/gradientView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerVertical="true"
            android:layout_marginLeft="@dimen/gradient_view_margin_left"
            prvandroid:StringToShow="@string/slide_to_unlock_string"
            prvandroid:TextSize="@dimen/gradient_text_size"
            prvandroid:TextColor="@color/gradient_text_color"
            prvandroid:SlideColor="@color/gradient_slide_text_color"/>
    </logdemo.wjj.com.logdemo.Custom.SlideBar>
</RelativeLayout>

IconEditText:http://blog.csdn.net/ddwhan0123/article/details/48654681

SlideBar,GradientView就是我们主要实现滑动解锁你的心的类了。

public class GradientView extends View {

    private static final  String  TAG = "GradientView";
    private static final boolean DEBUG = false;
    private float   mIndex = 0;
    private Shader  mShader;
    private int     mTextSize;
    private static final int mUpdateStep = 15;
    private static final int mMaxWidth = 40 * mUpdateStep; // 26*25
    private static final int mMinWidth = 6 * mUpdateStep;  // 5*25
    int             mDefaultColor;
    int             mSlideColor;
    private ValueAnimator animator;
    private int mWidth,mHeight;
    private String mStringToShow;
    private Paint mTextPaint;
    private float mTextHeight;
    private Drawable mSlideIcon;
    private int mSlideIconHeight;
    private static final int mSlideIconOffSetTop = 2;

    private AnimatorUpdateListener mAnimatorUpdateListener = new AnimatorUpdateListener() {

        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            mIndex =Float.parseFloat(animation.getAnimatedValue().toString());
            // RadialGradient SweepGradient
            mShader = new LinearGradient(mIndex - 20 * mUpdateStep, 100,
                    mIndex, 100, new int[] { mDefaultColor, mDefaultColor, mDefaultColor,mSlideColor,
                    mSlideColor, mDefaultColor, mDefaultColor, mDefaultColor }, null,
                    Shader.TileMode.CLAMP);

            postInvalidate();

        }
    };

    public GradientView(Context context) {
        super(context);
    }

    public GradientView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GradientView);
        mStringToShow = a.getString(R.styleable.GradientView_StringToShow) ;
        mTextSize = (int)a.getDimension(R.styleable.GradientView_TextSize, 40);
        mDefaultColor = a.getColor(R.styleable.GradientView_TextColor, Color.GRAY);
        mSlideColor = a.getColor(R.styleable.GradientView_SlideColor, Color.WHITE);
        mSlideIcon = context.getResources().getDrawable(R.drawable.slide_icon);
        mSlideIconHeight = mSlideIcon.getMinimumHeight();
        a.recycle();

        animator = ValueAnimator.ofFloat(mMinWidth,mMaxWidth);
        animator.setDuration(1800);
        animator.addUpdateListener(mAnimatorUpdateListener);
        animator.setRepeatCount(Animation.INFINITE);//repeat animation
        animator.start();

        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setColor(mSlideColor);
        mTextPaint.setTextSize(mTextSize);
        mTextPaint.setTextAlign(Paint.Align.CENTER);

        mTextHeight = mTextPaint.ascent();

        setFocusable(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if(DEBUG)
        Log.w(TAG, "b onDraw()");
        mTextPaint.setShader(mShader);
        canvas.drawBitmap(((BitmapDrawable) mSlideIcon).getBitmap(), 20, mHeight
                / 2 - mSlideIconHeight / 2 + mSlideIconOffSetTop, null);
        canvas.drawText(mStringToShow, mWidth / 2, mHeight / 2 - mTextHeight
                / 2 - mSlideIconOffSetTop, mTextPaint); // slide_unlock
    }

    public void stopAnimatorAndChangeColor() {
        Log.w(TAG, "stopGradient");
        animator.cancel();
        //reset
        mShader = new LinearGradient(0, 100, mIndex, 100,
                new int[] {mSlideColor, mSlideColor},
                null, Shader.TileMode.CLAMP);
        invalidate();
    }

    public void startAnimator() {
        if(DEBUG)
        Log.w(TAG, "startGradient");
        animator.start();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth = MeasureSpec.getSize(widthMeasureSpec);
        mHeight = MeasureSpec.getSize(heightMeasureSpec);
    }

    public void resetControl(){
        animator.start();
        this.setX(0);
        invalidate();
    }
}

SlideBar

public class SlideBar extends RelativeLayout {

    private static final String TAG = "SlideBar";
    private static final boolean DEBUG = false;

    GradientView mGradientView ;
    private int gradientViewStartX;
    private float mEventDownX;
    private float mGradientViewIndicateLeft;
    private OnTriggerListener mOnTriggerListener;
    private VelocityTracker mVelocityTracker = null;
    private int mMinVelocityXToUnlock;
    private int mMinDistanceToUnlock;
    private int mLeftAnimationDuration;
    private int mRightAnimationDuration;
    private ObjectAnimator animLeftMoveAnimator;
    private ObjectAnimator animRightMoveAnimator;
    private static final int MaxDistance = 400;

    public interface OnTriggerListener {
         void onTrigger();
    }

    public SlideBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    public SlideBar(Context context){
        super(context);
    }

    private void initView(Context context,AttributeSet attrs){
        gradientViewStartX = context.getResources().
                getDimensionPixelSize(R.dimen.gradient_view_margin_left) + 8;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlideBar);
        mMinVelocityXToUnlock = a.getInt(R.styleable.SlideBar_MinVelocityXToUnlock,2000) ;
        mMinDistanceToUnlock = a.getInt(R.styleable.SlideBar_MinDistanceToUnlock,300) ;
        mLeftAnimationDuration = a.getInt(R.styleable.SlideBar_LeftAnimationDuratioin,250) ;
        mRightAnimationDuration = a.getInt(R.styleable.SlideBar_RightAnimationDuratioin,300) ;
        a.recycle();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        final int action = event.getActionMasked();
        boolean handled = false;

        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }

        mVelocityTracker.addMovement(event);

        switch (action) {
            case MotionEvent.ACTION_POINTER_DOWN:
            case MotionEvent.ACTION_DOWN:
                if (DEBUG) Log.v(TAG, "*** DOWN ***");
                handleDown(event);
                handled = true;
                break;

            case MotionEvent.ACTION_MOVE:
                if (DEBUG) Log.v(TAG, "*** MOVE ***");
                handleMove(event);
                handled = true;
                break;

            case MotionEvent.ACTION_POINTER_UP:
            case MotionEvent.ACTION_UP:
                if (DEBUG) Log.v(TAG, "*** UP ***");
                handleUp(event);
                handled = true;
                break;

            case MotionEvent.ACTION_CANCEL:
                if (DEBUG) Log.v(TAG, "*** CANCEL ***");
                handled = true;
                break;

        }
        invalidate();
        return handled ? true : super.onTouchEvent(event);
    }

    public void handleUp(MotionEvent event) {

        Log.v(TAG, "handleUp,mIndicateLeft:" + mGradientViewIndicateLeft);
        //1. 如果用户滑动一些距离,解锁
        if(mGradientViewIndicateLeft >= mMinDistanceToUnlock){
            unlockSuccess();
            return;
        }
        //2. 如果用户滑动很快,解锁
        if(velocityTrigUnlock()){
            return;
        }
        resetControls();
    }

    /**
     * 另一种方式来解锁,如果用户滑动非常快
     */
    private boolean velocityTrigUnlock() {
        final VelocityTracker velocityTracker = mVelocityTracker;
        velocityTracker.computeCurrentVelocity(1000);

        int velocityX = (int) velocityTracker.getXVelocity();

        Log.v(TAG, "velocityX:" + velocityX);

        if(velocityX > mMinVelocityXToUnlock){
            unlockSuccess();
            return true;
        }

        if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
        return false;
    }

    private void unlockSuccess() {
        mOnTriggerListener.onTrigger();
        animRightMoveAnimator = ObjectAnimator.ofFloat(mGradientView, "x",mGradientView.getX(), MaxDistance)
                .setDuration(mRightAnimationDuration);
        animRightMoveAnimator.start();
    }

    private void handleMove(MotionEvent event) {

        mGradientViewIndicateLeft = event.getX() - mEventDownX + gradientViewStartX;
        if(mGradientViewIndicateLeft <= gradientViewStartX){
            mGradientViewIndicateLeft = gradientViewStartX;
        }
        mGradientView.setX(mGradientViewIndicateLeft);
    }

    private void handleDown(MotionEvent event) {
        mEventDownX = event.getX();
        if(mGradientView == null){
            mGradientView = (GradientView) findViewById(R.id.gradientView);
        }
        mGradientView.stopAnimatorAndChangeColor();

    }

    public void setOnTriggerListener(OnTriggerListener listener) {
        mOnTriggerListener = listener;
    }

    private void resetControls(){
        mGradientView.startAnimator();
        animLeftMoveAnimator = ObjectAnimator.ofFloat(mGradientView, "x", mGradientView.getX(),gradientViewStartX).setDuration(mLeftAnimationDuration);
        animLeftMoveAnimator.start();
    }

}

attrs:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="IconEditText">
        <attr name="iconSrc" format="reference" />
        <attr name="isPassword" format="boolean" />
        <attr name="hint" format="string"/>
    </declare-styleable>

    <declare-styleable name="GradientView">
        <attr name="StringToShow" format="reference"/>
        <attr name="TextSize" format="dimension"/>
        <attr name="TextColor" format="integer"/>
        <attr name="SlideColor" format="integer"/>
    </declare-styleable>

    <declare-styleable name="SlideBar">
        <attr name="MinVelocityXToUnlock" format="integer"/>
        <attr name="MinDistanceToUnlock" format="integer"/>
        <attr name="LeftAnimationDuratioin" format="integer"/>
        <attr name="RightAnimationDuratioin" format="integer"/>
    </declare-styleable>

</resources>

源码地址:http://download.csdn.net/detail/ddwhan0123/9143841

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-03 11:20:56

改写控件之《仿iOS滑动枷锁样式的登录》的相关文章

Android学习笔记(九)——布局和控件的自定义

//此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! View是 Android中一种最基本的 UI组件,它可以在屏幕上绘制一块矩形区域,并能响应这块区域的各种事件,因此,我们使用的各种控件其实就是在 View的基础之上又添加了各自特有的功能.而ViewGroup 则是一种特殊的 View,它可以包含很多的子 View和子 ViewGroup,是一个用于放置控件和布局的容器.系统默认的所有控件都是直接或间接继承自 View 的,所用的所有布局都是直接或间接继承自 Vie

UI基本控件和自定义视图

UILabel 常用属性: UITextField 常用属性: 输入控制属性: 外观控制属性: 输入框让键盘回收的方法: 1.通过协议 (1)让AppDelegate成为输入框的代理对象 ,让TA去执行事件(AppDelegate接受输入框的协议) (2)接受了协议就要执行键盘回收的方法 (3)建立关系: 如:textField.delegate = self;(self指AppDelegate) 2.通过Tag值 (1)创建一个按钮添加触发事件,让Tag值的键盘回收 (2)按钮触发的事件方法如

使用谷歌提供的SwipeRefreshLayout下拉控件,并自定义实现下拉加载的功能

package com.loaderman.swiperefreshdemo; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.View;

[转]一步一步玩控件:自定义TabControl——从山寨Safari开始

作者:野比 ([email protected]) 时间:May, 2012 封面图片为野比原创,请勿未经允许私自引用 #1-1 嗯,各位,又是我,生物钟颠倒的家伙. 今天我要山寨的是大名鼎鼎的Apple,传说中的「被山寨之王」. 没错,都被我山寨好几次了. 说起Apple,相信大家对他家的各种产品,不管他软还是硬,都有相当的好感. 最近Apple把自家的Web浏览器Safari升级到了第5版,并同步推出了Windows版,支持WinXP开始的全部Windows版本. 不得不说,这是一个很给力的

【转】C# 控件的自定义拖动、改变大小方法

在用VS的窗体设计器时,我们可以发现控件都是可以拖动的,并且还可以调整大小.怎么在自己的程序中可以使用上述功能呢? 下面的方法值得借鉴! using System; using System.Windows.Forms; using System.Drawing; namespace ControlSizeChangeEx { /// <summary> /// This class implements sizing and moving functions for /// runtime

WPF自定义控件与样式(10)-进度控件ProcessBar自定义样

一.前言 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等,若有不明白的地方可以参考本系列前面的文章,文末附有部分文章链接. 本文主要内容: ProcessBar自定义标准样式: ProcessBar自定义环形进度样式: 二.ProcessBar标准样式 效果图: ProcessBar的样式非常简单: <!--ProgressBar Style--> <Style TargetType="ProgressBar" x

UIButton图片文字控件位置自定义(图片居右文字居左、图片居中文字居中、图片居左文字消失等)

在开发中经常会碰到需要对按钮中的图片文字位置做调整的需求.第一种方式是通过设置按钮中图片文字的偏移量.通过方法setTitleEdgeInsets和setImageEdgeInsets实现 代码如下: /*!**方式一***/ - (void)updateBtnStyle_rightImage:(UIButton *)btn { CGFloat btnImageWidth = btn.imageView.bounds.size.width; CGFloat btnLabelWidth = btn

vue表单控件绑定+自定义组件

vue表单控件绑定 v-model 在表单控件元素上创建双向数据绑定 文本框双向绑定 多选框演示 下拉列表演示 vue自定义组件 组件放在components目录下 组件基本要素:props  $emit 通过import导入自定义组件 制作一个倒计时组件: 1.在conponents目录下,新建一个time.vue 方法写在mouted声明周期函数内,代码如下: 然后在index.vue中使用组件: 我之前组件命名为time,可能与默认什么冲突了,然后报错不让用,所以改名成cyytime 但是

C# 控件的自定义拖动、改变大小方法

在用VS的窗体设计器时,我们可以发现控件都是可以拖动的,并且还可以调整大小.怎么在自己的程序中可以使用上述功能呢? 下面的方法值得借鉴! using System; using System.Windows.Forms; using System.Drawing; namespace ControlSizeChangeEx { /// <summary> /// This class implements sizing and moving functions for /// runtime