編輯:關於 Android 程式設計
這是一個功能完整的小型登入範例,除了帳號密碼輸入,還包含「記住密碼」勾選框,以及把資訊寫入私有檔案、下次啟動自動回顯的邏輯。

<?xml version="1.0"?> -<LinearLayout android:paddingTop="@dimen/activity_vertical_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:orientation="vertical" android:layout_height="match_parent" android:layout_width="match_parent" xmlns:tools="https://schemas.android.com/tools" xmlns:android="https://schemas.android.com/apk/res/android"> <EditText android:id="@+id/et_username" android:layout_height="wrap_content" android:layout_width="fill_parent" android:hint="@string/input_username"/> <EditText android:id="@+id/et_password" android:layout_height="wrap_content" android:layout_width="fill_parent" android:hint="@string/input_password" android:inputType="textPassword" android:layout_marginBottom="10dp" android:layout_marginTop="10dp"/> -<RelativeLayout android:layout_height="wrap_content" android:layout_width="fill_parent"> <CheckBox android:id="@+id/cb_rem" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/rem_password" android:layout_alignParentLeft="true" android:layout_centerVertical="true"/> <Button android:id="@+id/bt_login" android:paddingRight="50dp" android:paddingLeft="50dp" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/login" android:layout_centerVertical="true" android:layout_alignParentRight="true"/> </RelativeLayout> </LinearLayout>
package com.itheima.login; import java.util.Map; import com.itheima.login.util.UserInfoUtil; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener{ private EditText et_username; private EditText et_password; private CheckBox cb_rem; private Button bt_login; private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; et_username = (EditText) findViewById(R.id.et_username); et_password = (EditText) findViewById(R.id.et_password); cb_rem = (CheckBox) findViewById(R.id.cb_rem); bt_login = (Button) findViewById(R.id.bt_login); //b.設置按鈕的點擊事件 bt_login.setOnClickListener(this); //f.回顯用戶名密碼 ?? Map<String, String> map = UserInfoUtil.getUserInfo_android(mContext);//獲取用戶名密碼 if(map != null){ String username = map.get("username"); String password = map.get("password"); et_username.setText(username);//設置用戶名 et_password.setText(password); cb_rem.setChecked(true);//設置復選框選中狀態 } } private void login(){ //c.在onclick方法中,獲取用戶輸入的用戶名密碼和是否記住密碼 String username = et_username.getText().toString().trim(); String password = et_password.getText().toString().trim(); boolean isrem = cb_rem.isChecked(); //d.判斷用戶名密碼是否為空,不為空請求服務器(省略,默認請求成功) if(TextUtils.isEmpty(username) || TextUtils.isEmpty(password)){ Toast.makeText(mContext, "用戶名密碼不能為空", Toast.LENGTH_SHORT).show(); return ; } //請求服務器,後面講。。。。。。。。。。 //e.判斷是否記住密碼,如果記住,將用戶名密碼保存本地。???? if(isrem){ boolean result = UserInfoUtil.saveUserInfo_android(mContext,username,password); if(result){ Toast.makeText(mContext, "用戶名密碼保存成功", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(mContext, "用戶名密碼保存失敗", Toast.LENGTH_SHORT).show(); } }else{ Toast.makeText(mContext, "無需保存", Toast.LENGTH_SHORT).show(); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.bt_login: login(); break; default: break; } } }
package com.itheima.login.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import android.content.Context; public class UserInfoUtil { //保存用戶名密碼 public static boolean saveUserInfo_android(Context context,String username, String password) { try{ String userinfo = username + "##"+ password;//封裝用戶名密碼 //得到私有目錄下一個文件寫入流; name : 私有目錄文件的名稱 mode: 文件的操作模式, 私有,追加,全局讀,全局寫 FileOutputStream fileOutputStream = context.openFileOutput("userinfo.txt", Context.MODE_PRIVATE); fileOutputStream.write(userinfo.getBytes());//將用戶名密碼寫入文件 fileOutputStream.close(); return true; }catch (Exception e) { e.printStackTrace(); } return false; } //獲取用戶名密碼 public static Map<String ,String> getUserInfo_android(Context context){ try{ //通過context對象獲取一個私有目錄的文件讀取流 FileInputStream fileInputStream = context.openFileInput("userinfo.txt"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream)); //讀取一行中包含用戶密碼,需要解析 String readLine = bufferedReader.readLine(); String[] split = readLine.split("##"); HashMap<String, String> hashMap = new HashMap<String ,String>(); hashMap.put("username", split[0]); hashMap.put("password", split[1]); bufferedReader.close(); fileInputStream.close(); return hashMap; }catch (Exception e) { e.printStackTrace(); } return null; } //保存用戶名密碼 public static boolean saveUserInfo(Context context,String username, String password) { try{ String userinfo = username + "##"+ password;//封裝用戶名密碼 // String path = "/data/data/com.itheima.login/";//指定保存的路徑 //通過Context對象獲取私有目錄的一個路徑 String path = context.getFilesDir().getPath(); System.out.println("...............:"+path); File file = new File(path,"userinfo.txt");//創建file FileOutputStream fileOutputStream = new FileOutputStream(file);//創建文件寫入流 fileOutputStream.write(userinfo.getBytes());//將用戶名密碼寫入文件 fileOutputStream.close(); return true; }catch (Exception e) { e.printStackTrace(); } return false; } //獲取用戶名密碼 public static Map<String ,String> getUserInfo(Context context){ try{ // String path = "/data/data/com.itheima.login/";//指定保存的路徑 //通過Context對象獲取私有目錄的一個路徑 String path = context.getFilesDir().getPath(); System.out.println("...............:"+path); File file = new File(path,"userinfo.txt");//創建file FileInputStream fileInputStream = new FileInputStream(file); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream)); //讀取一行中包含用戶密碼,需要解析 String readLine = bufferedReader.readLine(); String[] split = readLine.split("##"); HashMap<String, String> hashMap = new HashMap<String ,String>(); hashMap.put("username", split[0]); hashMap.put("password", split[1]); bufferedReader.close(); fileInputStream.close(); return hashMap; }catch (Exception e) { e.printStackTrace(); } return null; } }
Alt+Enter 補全抽象方法;用 field 快速提取全域變數;記得格式化程式碼;點擊事件用全域宣告;很多畫面都會用到 Context,乾脆在類別裡定義成成員,onCreate 中賦值 this,之後 Toast 直接取用;Ctrl+1 可以把你臨時打的程式碼封裝成新的類別。
1. 寫入檔案的流程
(1)決定存到私有目錄(/data/data/包名/);(2)取得路徑,用 context.getFilesDir().getPath() 比自己寫死好;(3)建立 File 物件(路徑+檔名);(4)建立 FileOutputStream,把 File 傳進去;(5)讀寫都要用 try 包住、catch 印出資訊;(6)write 只能收位元組,所以字串得先 getBytes();但帳號與密碼是兩個值怎麼辦?用 ## 之類「不會出現在正則表達式裡」的特殊字元串接,讀回來再用 split 切開;(7)最後 close() 關流;(8)return true 告知呼叫端成功。
2. 讀取與回顯的流程
(1)頁面一載入就回顯;(2)先判斷檔案是否存在;(3)路徑與檔名要和寫入時一致;(4)建立 FileInputStream;(5)帳號密碼在同一行,用 BufferedReader 的 readLine 一次讀出;(6)用 split 切開;(7)放進 HashMap 回傳;(8)關閉串流。
最後要補一句安全提醒:這個範例把密碼以純文字寫入檔案,只用於教學示範。正式專案請勿如此,應改用 hashed 儲存(例如加鹽雜湊),或交由系統的 Keystore 管理憑證,並在 Android 6.0 以上注意私有目錄的備份規則。
Android AIDL 跨進程傳遞自訂對象:Parcelable 打包與解包完整實作
黑夜給了我黑色的眼睛,我卻用它尋找光明。 跨進程傳值的幾種選擇 AIDL 天生支援跨進程傳值,實務上常見三類做法: · 廣播:最常見,傳小數據合適,缺點是承載量有限
自製 Android 控件實作:Well Swipe 拖拽排序與刪除動畫
最近動手寫了一個名為 Well Swipe 的客製化控件,主要解決列表項目的手勢互動問題,整體重點放在兩個體驗細節上。 核心功能 這個控件主要實現了兩件事:一是項目左右滑
Andrew Stankevich's Contest 題解彙編
本文整理自 Andrew Stankevichs Contest 的一系列補題題解,涵蓋數學規律、上下界網絡流、LIS、線段樹與 DFS 剪枝等經典算法,每題附上思路與參
ViewAnimator 與其子類 ViewSwitcher:仿 Launcher 的分頁切換
ViewAnimator 繼承自 FrameLayout,特性是「多個子 View 疊在同一個位置,切換時可套用動畫」。它有一個常用的子類 ViewSwitcher,特別