仿qq实现的记住密码和下拉框功能,简单易懂,还有背景炫酷的登录背景动画功能还有扫码

登录使用的异步线程进行的认证,扫码使用的是zxing的二维码扫描,个人不太会说,直接上代码,简单易懂,如果看不懂的话,我会上传资源,尽可以
下载
package com.baiyatech.shs.enterprise.activities;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baiyatech.shs.enterprise.R;
import com.baiyatech.shs.enterprise.scancodelogin.android.CaptureActivity;
import com.baiyatech.shs.enterprise.util.JellyInterpolator;
import com.baiyatech.shs.enterprise.util.SessionManager;
import com.baiyatech.shs.enterprise.util.ServerUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class LoginActivity extends Activity implements AdapterView.OnItemClickListener, PopupWindow.OnDismissListener {

    SessionManager sessionManager;

    private String username, password;
    private EditText usernameEditText, passwordEditText;
    private ImageView backgroundImageView;
    private Button loginButton;
    private View progress;
    private View mInputLayout;
    private float mWidth, mHeight;
    private CheckBox checkboxButton;
    SharedPreferences sp = null;
    private TextView saomalogin;
    private static final int REQUEST_CODE_SCAN = 0x0000;
    private static final String DECODED_CONTENT_KEY = "codedContent";
    private static final String DECODED_BITMAP_KEY = "codedBitmap";
    private String content;
    private ImageView user_show;
    private ArrayList mList = new ArrayList();
    private boolean mInitPopup;
    private PopupWindow mPopup;
    private boolean mShowing;
    private ArrayAdapter mAdapter;
    private ListView mListView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setTitle("智能家庭系统");
        usernameEditText = (EditText) findViewById(R.id.usernameEditText);
        passwordEditText = (EditText) findViewById(R.id.passwordEditText);
        sp = this.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        initView();
        sessionManager = new SessionManager(getApplicationContext());
        //按钮监听器
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                username = usernameEditText.getText().toString().trim();
                password = passwordEditText.getText().toString().trim();

                if (username == null || username.equals("")) {

                    Toast.makeText(LoginActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    // 计算出控件的高与宽
                    mWidth = loginButton.getMeasuredWidth();
                    mHeight = loginButton.getMeasuredHeight();
                    // 隐藏输入框
                    usernameEditText.setVisibility(View.INVISIBLE);
                    passwordEditText.setVisibility(View.INVISIBLE);
                    user_show.setVisibility(View.INVISIBLE);
                    inputAnimator(mInputLayout, mWidth, mHeight);
                    HashMap, String> userParams = new HashMap, String>();
                    userParams.put("username", username);
                    userParams.put("password", password);

                    AuthUserTask authUserTask = new AuthUserTask();
                    authUserTask.execute(userParams);
                    boolean CheckBoxLogin = checkboxButton.isChecked();
                    if (CheckBoxLogin)
                    {
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("uname", username);
                        editor.putString("upswd", password);
                        editor.putBoolean("checkboxBoolean", true);
                        editor.commit();
                    }
                    else
                    {
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("uname", null);
                        editor.putString("upswd", null);
                        editor.putBoolean("checkboxBoolean", false);
                        editor.commit();
                    }
                }
            }

        });
    }

    //在这里进行登录界面的新增控件的初始化以及新增登录界面的动画
    private void initView() {
        backgroundImageView = (ImageView) findViewById(R.id.login_background);
        loginButton = (Button) findViewById(R.id.main_btn_login);
        progress = findViewById(R.id.layout_progress);
        mInputLayout = findViewById(R.id.input_layout);
        checkboxButton = (CheckBox) findViewById(R.id.checkBoxLogin);
        saomalogin = (TextView) findViewById(R.id.saomalogin);
        user_show = (ImageView) findViewById(R.id.user_show);
        init();
        user_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mList!=null && mList.size()>0 && !mInitPopup){
                    mInitPopup = true;
                    initPopup();
                }
                if (mPopup != null) {
                    if (!mShowing) {
                        mPopup.showAsDropDown(usernameEditText, 0, -5);
                        mShowing = true;
                    } else {
                        mPopup.dismiss();
                    }
                }
                }
        });
        saomalogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(LoginActivity.this,CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SCAN);
            }
        });
        if (sp.getBoolean("checkboxBoolean", false)){
            usernameEditText.setText(sp.getString("uname", null));
            passwordEditText.setText(sp.getString("upswd", null));
            checkboxButton.setChecked(true);
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Animation animation = AnimationUtils.loadAnimation(LoginActivity.this, R.anim.translate_anim);
                backgroundImageView.startAnimation(animation);
            }
        }, 200);
    }

    private void initPopup() {
        mAdapter = new ArrayAdapter(this,
                android.R.layout.simple_dropdown_item_1line, mList);
        mListView = new ListView(this);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
        int height = ViewGroup.LayoutParams.WRAP_CONTENT;
        int width = usernameEditText.getWidth();
        System.out.println(width);
        mPopup = new PopupWindow(mListView, width, height, true);
        mPopup.setOutsideTouchable(true);
        mPopup.setBackgroundDrawable(getResources().getDrawable(
                    R.drawable.popup_bg));
        mPopup.setOnDismissListener(this);
    }

    private void init() {
        ObjectInputStream in=null;
        try {
            InputStream is=openFileInput("user_show.obj");
            in=new ObjectInputStream(is);
            mList=(ArrayList)in.readObject();
            if (mList.size()>0){
                usernameEditText.setText(mList.get(mList.size()-1));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally {
            if (in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String input = usernameEditText.getText().toString();
        mList.remove(input);
        mList.add(input);
        if (mList.size() > 5) {
            mList.remove(0);
        }
        ObjectOutputStream out = null;
        try {
            FileOutputStream os = openFileOutput("user_show.obj",
                    MODE_PRIVATE);
            out = new ObjectOutputStream(os);
            out.writeObject(mList);
        } catch (Exception e) {
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                content = data.getStringExtra(DECODED_CONTENT_KEY);
                Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);
                passwordEditText.setText(content);
                Log.e("解码结果: \n" , content);
            }
        }
    }

    private void inputAnimator(final View view, float w, float h) {

        AnimatorSet set = new AnimatorSet();

        ValueAnimator animator = ValueAnimator.ofFloat(0, w);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (Float) animation.getAnimatedValue();
                ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view
                        .getLayoutParams();
                params.leftMargin = (int) value;
                params.rightMargin = (int) value;
                view.setLayoutParams(params);
            }
        });

        ObjectAnimator animator2 = ObjectAnimator.ofFloat(mInputLayout,
                "scaleX", 1f, 0.5f);
        set.setDuration(1000);
        set.setInterpolator(new AccelerateDecelerateInterpolator());
        set.playTogether(animator, animator2);
        set.start();
        set.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                /**
                 * 动画结束后,先显示加载的动画,然后再隐藏输入框
                 */
                progress.setVisibility(View.VISIBLE);
                progressAnimator(progress);
                mInputLayout.setVisibility(View.INVISIBLE);

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }
        });

    }

    /**
     * 出现进度动画
     *
     * @param view
     */
    private void progressAnimator(final View view) {
        PropertyValuesHolder animator = PropertyValuesHolder.ofFloat("scaleX",
                0.5f, 1f);
        PropertyValuesHolder animator2 = PropertyValuesHolder.ofFloat("scaleY",
                0.5f, 1f);
        ObjectAnimator animator3 = ObjectAnimator.ofPropertyValuesHolder(view,
                animator, animator2);
        animator3.setDuration(1000);
        animator3.setInterpolator(new JellyInterpolator());
        animator3.start();

    }

    //处理返回键
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN
                && event.getRepeatCount() == 0) {
            new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("确定退出点点亮程序?")
                    .setContentText("Confirm exit point lighting program again")
                    .setConfirmText("确定")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            finish();
                        }
                    })
                    .show();
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onItemClick(AdapterView adapterView, View view, int position, long l) {
        usernameEditText.setText(mList.get(position));
        mPopup.dismiss();
    }

    @Override
    public void onDismiss() {
        mShowing = false;
    }

    /**
     * 异步进程与服务器进行用户验证
     */
    private class AuthUserTask extends AsyncTask, String>, String, Boolean> {

        ProgressDialog progressDialog;

        //XD: constructor to passwordEditText context
        AuthUserTask() {
        }

        protected void onPreExecute() {
            // progressDialog = ProgressDialog.show(LoginActivity.this, "", "正在登录...");
        }

        protected Boolean doInBackground(HashMap, String>... userParams) {
            try {
                sessionManager.loadServerConfig();
                String authDataResponse = ServerUtils.fetchData(sessionManager.getServerConfig("URL_User_Auth"), userParams[0], getApplicationContext());
                JSONArray authData = new JSONArray(authDataResponse);
                for (int i = 0; i < authData.length(); i++) {
                    JSONObject authDataJSONObject = authData.getJSONObject(i);
                    int roomID = authDataJSONObject.getInt("room_id");
                    if (authDataJSONObject.getString("username").equals(username) && (authDataJSONObject.getBoolean("password"))) {
                        sessionManager.createUserSession(username, roomID);
                        return true;
                    } else {
                        return false;
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return false;
        }

        protected void onProgressUpdate(String... values) {

        }

        protected void onCancelled() {
            progressDialog.dismiss();
        }


        protected void onPostExecute(Boolean authSucceed) {
            if (authSucceed) {
                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            } else {
                Toast.makeText(LoginActivity.this, "用户名或密码错误,请重新登录", Toast.LENGTH_SHORT).show();
            }
            if(progressDialog!=null){
                progressDialog.dismiss();
            }
        }
    }
}

你可能感兴趣的:(仿qq实现的记住密码和下拉框功能,简单易懂,还有背景炫酷的登录背景动画功能还有扫码)