登录案例
- 从三面入手 画页面 根据UI写逻辑 测试.
- 代码实现[1]:画ui
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入用户名" /> <EditText android:id="@+id/et_pwd" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入密码" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <CheckBox android:id="@+id/cb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="保存密码" /> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_toRightOf="@id/cb" android:text="登录" /> </RelativeLayout> </LinearLayout>
- [2]根据ui写对应的业务逻辑
- [2.1]登录流程如下:
- [2.2]把用户名和密码保存起来 由于保存数据和读取数据业务逻辑是独立的所以单独写到一个工具类里
public void ReadFile() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File sdcardDir = Environment.getExternalStorageDirectory(); try { FileInputStream fis = new FileInputStream(sdcardDir.getCanonicalPath() + "/info.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); Log.e(TAG, "ReadFile: " + sb.toString()); HashMap<String, String> map = new HashMap<>(); final String[] split = sb.toString().split("##"); int length = split.length; Log.e(TAG, "onCreate: " + split.length); map.put("name", split[0]); map.put("pwd", split[1]); runOnUiThread(new Runnable() { @Override public void run() { mEtName.setText(split[0]); mEtPwd.setText(split[1]); mCb.setChecked(true); } }); } catch (IOException e) { e.printStackTrace(); } } } public boolean writeFile(String name, String pwd) { String content = name + "##" + pwd; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File sdcarDir = Environment.getExternalStorageDirectory(); try { FileOutputStream fos = new FileOutputStream(sdcarDir.getCanonicalPath() + "/info.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw); bw.write(content); // content为你需要写入的字符串 bw.close(); return true; /* 等价于 new BufferedWriter( new OutputStreamWriter( new FileOutputStream(sdcardDir.getCanonicalPath()+"wenjianming"))) .write("sfsd"); 但不知道怎么close哈哈 */ } catch (IOException e) { e.printStackTrace(); return false; } } return false; }
- [2.3]当保存数据就调用save方法 当读取数据就调用readinfo方法
原文地址:https://www.cnblogs.com/nangongyibin/p/10199789.html
时间: 2024-10-09 23:37:47