Android作业:使用SharedPreferences将姓名和年龄信息保存到文件,然后再读取
这次作业我修改了一下,没按照老师的要求来
没用年龄信息,用的是爱好
话不多说,直接进入正题
首先是xml的布局
<EditText android:id="@+id/etname" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="" android:hint="请输入姓名" /> <EditText android:id="@+id/ethobby" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="" android:hint="请输入爱好" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:onClick="onClick" android:id="@+id/write" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="写入"/> <Button android:onClick="onClick" android:id="@+id/read" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="读数"/> </LinearLayout>
然后是Java
private void read() { SharedPreferences prefs = getSharedPreferences("data", MODE_PRIVATE); String name=prefs.getString("name",""); String hobby=prefs.getString("hobby",""); Toast.makeText(MainActivity.this,"姓名:"+name+",爱好:"+hobby,Toast.LENGTH_SHORT).show(); } private void save(String name, String hobby) { SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit(); editor.putString("name",name); editor.putString("hobby",hobby); editor.commit(); Toast.makeText(MainActivity.this,"信息已经保存",Toast.LENGTH_SHORT).show(); } }
END