標籤(空格分隔): Androidjavascript
--java
思路:
就是使用sharePreference類存儲數據,並在特定的時候用Toast顯示存儲的數據
在建立sharePreference類的對象後調用它的getsharepreference方法指定要存放數據的文件,若是沒有系統自動建立這個文件,並設置文件的操做模式爲私有化(其餘應用沒法訪問)。而後建立sharePreference的editor來進行編輯。最後不要忘了調用editor對象的commit方法。讀取數據也是如法炮製。建立sharePreference對象和editor對象調用個體getString方法經過對應的鍵值獲得存儲的數據而後將它顯示出來android
佈局:app
<EditText android:id="@+id/edt_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/login" /> <View android:layout_width="match_parent" android:layout_height="1px" android:background="#000000"/> <EditText android:id="@+id/edt_age" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/age" /> <View android:layout_width="match_parent" android:layout_height="1px" android:background="#000000"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/write" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick" android:text="@string/save"/> <Button android:id="@+id/read" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick" android:text="@string/read"/>
java文件:佈局
1 獲取相關控件this
private Button write; private Button read; private EditText name; private EditText password; write = (Button)findViewById(R.id.write); read = (Button)findViewById(R.id.read); name = (EditText)findViewById(R.id.edt_name); password = (EditText)findViewById(R.id.edt_age);
2創建監聽事件3d
public void onClick(View view) { String username = name.getText().toString(); String password1 = password.getText().toString(); switch (view.getId()){ case R.id.write: saveToPre(username,password1); break; case R.id.read: readPre(); break; } }
saveToPre方法和readPre方法:code
private void readPre() { SharedPreferences sp = getSharedPreferences("name",MODE_PRIVATE); String username = sp.getString("xm",""); String age = sp.getString("m",""); name.setText(""); password.setText(""); Toast.makeText(this,"姓名是:" + username + " 年齡是:" + age,Toast.LENGTH_LONG).show(); } private boolean saveToPre(String username, String password) { SharedPreferences sp = getSharedPreferences("name",MODE_PRIVATE); SharedPreferences.Editor edit = sp.edit(); edit.putString("xm",username); edit.putString("m",password); edit.apply(); Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show(); return true; }
效果展現:
對象