Google Android Templates
緣由:從eclipse時(shí)代到“死丟丟”時(shí)代,一直存在一個(gè)我未曾深入觀察過的東西——Google Android Templates。一次偶然我在android studio上面結(jié)識了她,遂望一窺究竟。
How to Creat?標(biāo)題欄File→New→Activity→Login Activity,接下來在彈出的對話框中一直點(diǎn)擊Next直到點(diǎn)擊Filish。當(dāng)然上面所說的都是在你的model里面完成的。如下圖:
-
①
image -
②
image
To observe。拿到源碼第一件事我們不是修改,而是先進(jìn)行觀察。我是個(gè)喜歡從外到內(nèi)的人,所以我先run起來。
-
1.image
-
2.image
-
現(xiàn)象:
- 1.運(yùn)行時(shí)權(quán)限申請
- 2.兩個(gè)輸入框的提示性文字有動畫效果(且輸入內(nèi)容后未消失)。焦點(diǎn)轉(zhuǎn)移后能看到明顯的色彩變化。
- 3.點(diǎn)擊登錄按鈕后有針對email地址輸入框的錯(cuò)誤提示文字。
- 4.鍵盤下面有個(gè)獨(dú)特的@符號,一般情況下的英文輸入法是沒有單獨(dú)放在這么明顯地方的@符號。
- 5.符合效驗(yàn)標(biāo)準(zhǔn)后,點(diǎn)擊登錄按鈕會有進(jìn)度圈旋轉(zhuǎn)。
source code
-
activity_login.xml
<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:inputType="textEmailAddress" 說明軟件盤中會有@符號 --> </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>
- 上面代碼中包含控件:ProgressBar、ScrollView、LinearLayout、TextInputLayout、EditText、Button。
-
分析:
- ProgressBar是我們登錄后出現(xiàn)的進(jìn)度條。
- ScrollView可滑動界面,內(nèi)部只能包含一個(gè)控件
- LinearLayout是ScrollView可滑動界面下面的最上層控件,有且僅有一個(gè)
- TextInputLayout文本輸入布局
- EditText輸入框
- Button按鈕,點(diǎn)擊后執(zhí)行登陸操作
- 在上面的控件中, 我們不是特別常用的僅僅有TextInputLayout,而且根據(jù)界面效果來看,我們大膽猜測TextInputLayout可能產(chǎn)生了EditText的提示文字(hint)發(fā)生了變化,故此我們需要查看相關(guān)資料和官方API文檔,根據(jù)文章總結(jié),TextInputLayout是一個(gè)顯示在EditText上方的浮動標(biāo)簽。跟ScrollView一樣,TextInputLayout只接受一個(gè)子元素。子元素需要是一個(gè)EditText元素。
- 展示效果:一個(gè)單一的EditText 在輸入文字的時(shí)候會隱藏hint,而被包含在TextInputLayout中的EditText則會讓hint變成一個(gè)在EditText上方的浮動標(biāo)簽。同時(shí)還包括一個(gè)漂亮的material動畫。
- 處理錯(cuò)誤:TextInputLayout可以處理錯(cuò)誤,我們先檢查輸入的信息是否正常,如果不符合我們的要求我們可以設(shè)置錯(cuò)誤XXX.setError();
- 樣式:TextInputLayout,所有色彩展示都是在style.xml中設(shè)置,具體的請自行搜索。
-
LoginActivity.java
/** * A login screen that offers login via 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[]{ "foo@example.com:hello", "bar@example.com: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) { 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("@"); } 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. 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. 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); } } }
- 分析:
- 方法列表:
- onCreate() ——來自activity,初始化控件,事件綁定。
- populateAutoComplete() ——調(diào)用mayRequestContacts(),成功后調(diào)用接口(LoaderCallbacks)下面的方法
- mayRequestContacts() ——?jiǎng)討B(tài)獲取PERMISSION_GRANTED(通訊錄權(quán)限)
- onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) ——顧名思義是返回權(quán)限申請的結(jié)果
- attemptLogin() ——登錄事件
- isEmailValid(String email) ——是否是email地址的標(biāo)準(zhǔn)
- isPasswordValid(String password) ——是否符合密碼標(biāo)準(zhǔn)
- showProgress(final boolean show) ——加載進(jìn)度條
- onCreateLoader(int i, Bundle bundle) ——接口LoaderCallbacks
- onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) ——接口LoaderCallbacks
- onLoaderReset(Loader<Cursor> cursorLoader) ——接口LoaderCallbacks
- addEmailsToAutoComplete(List<String> emailAddressCollection) ——
- 內(nèi)部接口:
- ProfileQuery
- 接口內(nèi)常量 String[] PROJECTION、ADDRESS、IS_PRIMARY
- ProfileQuery
- 內(nèi)部類:
-
UserLoginTask extends AsyncTask<Void, Void, Boolean>
- 構(gòu)造函數(shù):UserLoginTask(String email, String password)
- 方法:
- doInBackground(Void... params)
- onPostExecute(final Boolean success)
- onCancelled()
-
UserLoginTask extends AsyncTask<Void, Void, Boolean>
- 流程梳理:
- 1.加載XML布局→找到mEmailView控件(email輸入框)→申請通訊錄權(quán)限
- 申請權(quán)限成功→遍歷通訊錄→獲取主要的email→有,加載到界面、無,無操作
- 申請權(quán)限失敗→無操作
- 2.找到其他控件→事件綁定→等待用戶執(zhí)行操作
- 3.操作界面→執(zhí)行登錄事件
- 1.加載XML布局→找到mEmailView控件(email輸入框)→申請通訊錄權(quán)限
- 上面我們列出了方法列表,并且將我們涉及到主體流程、較新技能等的方法均有加粗標(biāo)記。
- 方法列表:
- 解析:
申請權(quán)限:
private boolean mayRequestContacts() { //當(dāng)系統(tǒng)版本低于android_M時(shí),跳過權(quán)限檢查 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } //當(dāng)系統(tǒng)版本大于等于android_M時(shí),執(zhí)行權(quán)限申請代碼 if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) { //當(dāng)自身已經(jīng)被允許的權(quán)限中包含了READ_CONTACTS時(shí),返回True return true; } //當(dāng)自身已經(jīng)被允許權(quán)限中沒有READ_CONTACTS時(shí),申請通訊錄讀取權(quán)限READ_CONTACTS //shouldShowRequestPermissionRationale ==> 是否需要調(diào)用系統(tǒng)的權(quán)限申請界面 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) { //展示請求權(quán)限界面,第一個(gè)參數(shù)是權(quán)限數(shù)組,第二個(gè)是請求碼 requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS); } }); } else { requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS); } return false; }
申請權(quán)限返回的響應(yīng)
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //請求碼 對應(yīng)上面請求的請求碼 if (requestCode == REQUEST_READ_CONTACTS) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //權(quán)限申請成功 populateAutoComplete(); //讀取聯(lián)系人列表內(nèi)的email } }}
登錄事件
private void attemptLogin() { if (mAuthTask != null) { //登錄信息提交的異步任務(wù)已經(jīng)實(shí)例化,則無需進(jìn)行操作,第一次執(zhí)行attemptLogin()時(shí),mAuthTask并未初始化 return; } // Reset errors.重設(shè)用戶名和密碼框的錯(cuò)誤提示 mEmailView.setError(null); //setError方法是TextView下面的方法,主要是提示一個(gè)錯(cuò)誤信息,內(nèi)部有系統(tǒng)集成的錯(cuò)誤提示圖標(biāo),原理是在TextView的右邊出現(xiàn)一個(gè)Drawable 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; //是否退出執(zhí)行登陸進(jìn)程 View focusView = null; //焦點(diǎn)View,當(dāng)某個(gè)輸入框輸入信息不符合標(biāo)準(zhǔn)時(shí),不執(zhí)行登陸進(jìn)程,并鎖定焦點(diǎn)到那個(gè)輸入控件 // 當(dāng)用戶名不為空,判斷密碼是否符合標(biāo)準(zhǔn) 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) { //在上面的操作中出現(xiàn)錯(cuò)誤了,不執(zhí)行具體的登錄,并且把焦點(diǎn)切換到上面去 // There was an error; don't attempt login and focus the first // form field with an error. focusView.requestFocus(); } else { //開啟滾動條,執(zhí)行登錄的異步任務(wù) // 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); } }
登錄的異步任務(wù)
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) { //后臺任務(wù),耗時(shí)操作此處執(zhí)行,該處代碼執(zhí)行在子線程 // TODO: attempt authentication against a network service. try { // Simulate network access. Thread.sleep(2000); //模擬耗時(shí)操作 } 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. return pieces[1].equals(mPassword); } } // TODO: register the new account here. return true; } @Override protected void onPostExecute(final Boolean success) { //執(zhí)行完畢耗時(shí)操作調(diào)用這里 mAuthTask = null; showProgress(false); if (success) { finish(); } else { mPasswordView.setError(getString(R.string.error_incorrect_password)); mPasswordView.requestFocus(); } } @Override protected void onCancelled() { //退出異步任務(wù)調(diào)用這里 mAuthTask = null; showProgress(false); } }
- 關(guān)于更多AsyncTask資料點(diǎn)擊查看
- 分析:
總結(jié):
- TextInputLayout,這個(gè)控件包含EditText后,會產(chǎn)生提示文字的動畫效果,且提示文字不會消失。
- 縱向布局中,為了保證界面能完整展示,最好在外層套上ScrollView。
- 一個(gè)簡單的登錄流程,耗時(shí)操作不能在主線程執(zhí)行,AsyncTask異步任務(wù)執(zhí)行完畢后,會回歸主線程。
- 需要數(shù)據(jù)交互的地方,數(shù)據(jù)需要做效驗(yàn)。
- (重點(diǎn))android6.0以及以后加入了權(quán)限申請,我們這里是動態(tài)權(quán)限申請,也是最容易被用戶接受的。
- 整個(gè)登陸界面的操作流程。