学习Android Studio开发工具之Activity3(框架2)

接上文学习Android Studio开发工具之Activity3(框架1)

本篇介绍Android Studio提供的用户登录框架,新建一个Module命名为Login,选择Login Activity,如图:

等待Android Studio编译完成安装到虚拟机后的效果如图:

可以看到使用ScrollView布局使得登录编辑框更加人性化。

先来看布局文件 activity_login.xml

<LinearLayout 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:gravity="center_horizontal"
              android:orientation="vertical"
              android:paddingBottom="@dimen/activity_vertical_margin"
              android:paddingLeft="@dimen/activity_horizontal_margin"
              android:paddingRight="@dimen/activity_horizontal_margin"
              android:paddingTop="@dimen/activity_vertical_margin"
              tools:context="com.hitsz.xiaokai.login.LoginActivity">

    <!-- Login progress -->
    <ProgressBar
        android:id="@+id/login_progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:visibility="gone"/>

    <ScrollView
        android:id="@+id/login_form"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/email_login_form"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <AutoCompleteTextView
                    android:id="@+id/email"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/prompt_email"
                    android:inputType="textEmailAddress"
                    android:maxLines="1"
                    android:singleLine="true"/>

            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/password"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/prompt_password"
                    android:imeActionId="@+id/login"
                    android:imeActionLabel="@string/action_sign_in_short"
                    android:imeOptions="actionUnspecified"
                    android:inputType="textPassword"
                    android:maxLines="1"
                    android:singleLine="true"/>

            </android.support.design.widget.TextInputLayout>

            <Button
                android:id="@+id/email_sign_in_button"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:text="@string/action_sign_in"
                android:textStyle="bold"/>

        </LinearLayout>
    </ScrollView>
</LinearLayout>

这里使用了扩展的控件AutoCompleteTextView,输入文本类型为textEmailAddress,用户输入时会检查类型是否满足要求,而且会自动保存用户Email账户到本地,下次登录会提示历史记录点击填充。这里需要在AndroidManifest中配置相应的权限。

权限声明:

    <!-- To auto-complete the email text field in the login form with the user‘s emails -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    <uses-permission android:name="android.permission.READ_PROFILE"/>
    <uses-permission android:name="android.permission.READ_CONTACTS"/>

接下来再看重要的登录实现逻辑框架:

package com.hitsz.xiaokai.login;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;

import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;

import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import static android.Manifest.permission.READ_CONTACTS;

/**
 * A login screen that offers login via email/password.
 * 登录界面有email和password两个输入框
 */
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {

    /**
     * Id to identity READ_CONTACTS permission request.
     * 读取用户通讯录
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     * 模拟授权的账户
     */
    private static final String[] DUMMY_CREDENTIALS = new String[]{
            "[email protected]:hello", "[email protected]:world"
    };
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     * 声明用户登录引用,方便随时撤销登录请求
     */
    private UserLoginTask mAuthTask = null;

    // UI references.界面控件
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();

        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            //当用户处在输入密码编辑框,软键盘打开,输入确定按钮(EditorInfo.IME_NUL)时尝试登录
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        //登录按钮点击事件
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

    //登录界面和进度条界面
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }
    //加载本地账户
    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }

        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                    .setAction(android.R.string.ok, new View.OnClickListener() {
                        @Override
                        @TargetApi(Build.VERSION_CODES.M)
                        public void onClick(View v) {
                            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                        }
                    });
        } else {
            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.在登录界面尝试注册登录账户,如果登录信息不满足要求显示出错信息
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        //检查密码有效性
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
    //取消登录
        if (cancel) {
            // There was an error; don‘t attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, password);
            mAuthTask.execute((Void) null);
        }
    }
    //判断邮箱有效性,必须含有"@"
    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        return email.contains("@");
    }

    //密码有效性判断,必须长度大于4
    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     * 显示进度条界面,关闭登录窗体
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this,
                // Retrieve data rows for the device user‘s ‘profile‘ contact.遍历用户的profile数据
                Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                        ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

                // Select only email addresses.选择邮箱地址
                ContactsContract.Contacts.Data.MIMETYPE +
                        " = ?", new String[]{ContactsContract.CommonDataKinds.Email
                .CONTENT_ITEM_TYPE},

                // Show primary email addresses first. Note that there won‘t be
                // a primary email address if the user hasn‘t specified one.按照用户的输入显示排序的邮箱地址
                ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }

        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {

    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.创建自动填充的提示列表适配器
        ArrayAdapter<String> adapter =
                new ArrayAdapter<>(LoginActivity.this,
                        android.R.layout.simple_dropdown_item_1line, emailAddressCollection);

        mEmailView.setAdapter(adapter);
    }

    private interface ProfileQuery {
        String[] PROJECTION = {
                ContactsContract.CommonDataKinds.Email.ADDRESS,
                ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
        };

        int ADDRESS = 0;
        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     * 显示异步登录注册任务,继承异步任务
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;
        private final String mPassword;

        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.通过网络服务尝试获取授权

            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }

            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the password matches.如果账户存在且密码匹配成功返回true
                    return pieces[1].equals(mPassword);
                }
            }

            // TODO: register the new account here.注册
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                finish();
            } else {
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }
    //取消任务
        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

时间: 2024-09-29 17:58:40

学习Android Studio开发工具之Activity3(框架2)的相关文章

学习Android Studio开发工具之Activity3(框架3)

接上文学习Android Studio开发工具之Activity3(框架2) 本篇介绍Android Studio提供的用户偏好设置,新建一个Module命名为Prefs,选择Settings Activity,如图: 运行的效果如图: SettingsActivity继承自AppCompatPreferenceActivity间接继承自PreferenceActivity,覆写方法onBuildHeaders(List<Header> target),在其方法内部加载视图资源文件 loadH

学习Android Studio开发工具之Activity1

Android Studio与EclipseADT存在着诸多不同之处,这里列举一些Android Studio相对Eclipse 比较棒的特性. 颜色.图片在布局和代码中可以实时预览 string可以实时预览 多屏预览.截图带有设备框,可随时录制模拟器视频 可以直接打开文件所在位置 跨工程移动.搜索.跳转 自动保存,无需一直Ctrl + S 即使文件关闭依然可以回退N个历史 智能重构.智能预测报错 每一行文件编辑历史,可追溯到人 各种插件例如ADB..gitignore.sql.markdown

学习Android Studio开发工具之Activity2(&amp;Fragment)

开篇先介绍几个放在眼前却经常忽视的快捷键如图: 展现出android Studio超强的搜索能力,提高大工程的开发维护效率. 双击Shift按键效果 Ctrl+Shift+N 根据文件名打开文件 Ctrl+E 打开最近文件 Alt+Home 定位导航栏 本篇是介绍Google推荐使用的fragment以及其与activity的通信. 新建一个BlankFragment, 其中自动生成的代码如下: package com.hitsz.xiaokai.fragmentcom; import andr

android studio开发工具的android library打包文件(.aar)本地引用

by 蔡建良 2014-5-13 关键点: 利用Gradle发布本地maven库支持android library 打包文件(*.aar) 的本地引用 开发环境: windows7 64位操作系统 android studio0.5.8 (1) 安装maven1.在安装maven之前,先确保已经安装JDK1.6及以上版本,并且配置好环境变量.2.下载maven3,最新版本是Maven3.2.1 ,下载地址:http://maven.apache.org/download.html 下载apach

[Android 新特性] 谷歌发布Android Studio开发工具1.0正式版(组图) 2014-12-09 09:35:40

Android Studio是谷歌于13年I/O大会推出的Android开发环境,基于IntelliJ IDEA. 类似 Eclipse ADT,Android Studio 提供了集成的Android开发工具用于开发和调试. 今日谷歌发布了Android studio的1.0正式版,增加了包括智能代码编辑,用户界面设计工具,性能分析工具等新功能,支持Android 5.0平台的开发. 谷歌也将推荐开发环境从Eclipse IDE调整为Android studio,还为Eclipse开发者提供了

Android Studio 开发工具基本设置

由于时间关系本文只简单说明作用: 1.Android Studio 背景颜色设置,个人喜欢这背景颜色.还有设置字体大小. 2.文件字符编码设置 3.快捷键使用 之前习惯使用 Eclipse 所以设置 4.自动导包设置 5.真机调试设置 首先真机设置开发者选项

Android studio开发工具设置默认编码

这段是用的是Google的开发工具,和Eclipse设置编码格式的时候有点区别,这里我分享给大家 第一步 File -->Settings打开设置面板 第二步在编码面板设置编码 应用一下就ok了

Android Studio 开发技巧详解

Android Studio开发工具是每一个 Android 程序猿每天都要使用的工具,但是即使你是一个经验丰富的开发人员,你也可能已经错过了许多可以节约生命的技巧,这篇文章也许就可以帮助你掌握它们其中的一部分.我不会一字一句地翻译,而是以最简洁易懂的方式介绍给你,同时提供必要的注解和延伸,让你可以在一遍快速阅读之后迅速掌握. 1.当你想不起来某个功能怎么用的时候 如果你是 Windows/Linux 用户, 那么请按Ctrl + Shift + A, 如果你是 Mac 用户,那么请按Comma

windows平台下Android studio开发环境搭建教程

最近,Google 已宣布,为了简化 Android 的开发力度,以重点建设 Android Studio 工具,到今年年底将停止支持Eclipse等其他集成开发环境 .而随着Android studio正式版的推出和完善,Android开发者们转向Android studio开发平台也将是大势所趋! 小弟Vike原先学习Android也是一直用的eclipse,虽然时间不长,而且用起来慢点,卡点,但是毕竟熟悉起来了,猛地要转到一个新平台,还真是相当不习惯.且不说快捷键有变化,就连Android