标签(空格分隔): 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; }
效果展现:
对象