改写控件之《仿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-07 08:46:56

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

Android 带清除功能的输入框控件ClearEditText,仿IOS的输入框

今天给大家带来一个很实用的小控件ClearEditText,就是在Android系统的输入框右边加入一个小图标,点击小图标可以清除输入框里面的内容,IOS上面直接设置某个属性就可以实现这一功能,但是Android原生EditText不具备此功能,所以要想实现这一功能我们需要重写EditText,接下来就带大家来实现这一小小的功能 我们知道,我们可以为我们的输入框在上下左右设置图片,所以我们可以利用属性android:drawableRight设置我们的删除小图标,如图 我这里设置了左边和右边的图

listview-怎样让上面的控件和Listview一起滑动

问题描述 怎样让上面的控件和Listview一起滑动 一个页面上有ListView,listView上面有其他控件,怎样让上面的控件和Listview一起滑动 解决方案 方法一:listview.addheadview,把那些控件作为headview添加到listview方法二:计算listview的高度(这里需要list中的item高度是固定的,textview这种要设定行数,不能高度可变),外套一层ScrollView 解决方案二: listview.addheadview,把那些控件作为h

全编辑WebGrid控件LrcGrid(4)—— 脚本库和样式表

web|脚本|控件|样式表 全编辑WebGrid控件LrcGrid(4)-- 脚本库和样式表 脚本库:包含了控件客户端操作的函数.包括: 将表格行切换到编辑模式的函数:chgEditRow(rowIndex,tab)() 将表格列切换到编辑模式的函数:chgEdit(colIndex,tab) 在客户端构造更新数据库的sql语句: BuildSql(tabName) 添加新记录的函数:AddRow(tab) 移除新添加行的函数: RemoveRow(tab)全部js代码: function ch

Android控件之RatingBar自定义星级评分样式_Android

一.RatingBar简单介绍 RatingBar是基于SeekBar(拖动条)和ProgressBar(状态条)的扩展,用星形来显示等级评定,在使用默认RatingBar时,用户可以通过触摸/拖动/按键(比如遥控器)来设置评分, RatingBar自带有两种模式 ,一个小风格 ratingBarStyleSmall,大风格为ratingBarStyleIndicator,大的只适合做指示,不适用与用户交互. 效果图展示: 二.实例 1.布局文件 <?xml version="1.0&qu

!小的在模版页中使用menu控件,点击菜单时选中样式不起作用。

问题描述 在模版页中使用menu控件,点击菜单时选中样式不起作用.各个页面都是基于这个模版生成的,现在是想点击上面的菜单有选中效果.在selectedstyle那里设定了属性,但每次点击时都不起作用,猜想是由于刷新的缘故???请各位大虾帮忙哦~~ 解决方案 解决方案二:我晕,一转眼就第二页去了,那么多大虾帮帮忙拉解决方案三:还是没有高手回答~我没描述清?还是问题太简单了?

Android控件之RatingBar自定义星级评分样式

一.RatingBar简单介绍 RatingBar是基于SeekBar(拖动条)和ProgressBar(状态条)的扩展,用星形来显示等级评定,在使用默认RatingBar时,用户可以通过触摸/拖动/按键(比如遥控器)来设置评分, RatingBar自带有两种模式 ,一个小风格 ratingBarStyleSmall,大风格为ratingBarStyleIndicator,大的只适合做指示,不适用与用户交互. 效果图展示: 二.实例 1.布局文件 <?xml version="1.0&qu

Android控件SeekBar仿淘宝滑动验证效果_Android

SeekBar是一个拖动条控件,最简单的案例就是我们的调节音量,还有音频视频的播放,传统的SeekBar样式,如图 传统的实现太简单,不足以让我们到能装逼的地步.本来是打算实现滴滴出行滑动完成订单的效果,可惜找不到效果图,今天也就用淘宝的滑动验证来作为实例 1.1 实现分析 SeekBar:使用progressDrawable属性自定义SeekBar 拖动块:使用thumb属性更改,其实就是一张图片 文字:使用RelativeLayout嵌套在一起 1.2 实现布局 <?xml version=

Android控件SeekBar仿淘宝滑动验证效果

SeekBar是一个拖动条控件,最简单的案例就是我们的调节音量,还有音频视频的播放,传统的SeekBar样式,如图 传统的实现太简单,不足以让我们到能装逼的地步.本来是打算实现滴滴出行滑动完成订单的效果,可惜找不到效果图,今天也就用淘宝的滑动验证来作为实例 1.1 实现分析 SeekBar:使用progressDrawable属性自定义SeekBar 拖动块:使用thumb属性更改,其实就是一张图片 文字:使用RelativeLayout嵌套在一起 1.2 实现布局 <?xml version=

Android控件PopupWindow模仿ios底部弹窗_Android

前言 在H5火热的时代,许多框架都出了底部弹窗的控件,在H5被称为弹出菜单ActionSheet,今天我们也来模仿一个ios的底部弹窗,取材于苹果QQ的选择头像功能. 正文 废话不多说,先来个今天要实现的效果图 整个PopupWindow的开启代码 private void openPopupWindow(View v) { //防止重复按按钮 if (popupWindow != null && popupWindow.isShowing()) { return; } //设置Popup