Android中SharedPreferences简单使用实例
程序员文章站
2023-12-17 18:35:10
本文实例为大家分享了sharedpreferences简单使用案例,供大家参考,具体内容如下
mainactivity:
public class shared...
本文实例为大家分享了sharedpreferences简单使用案例,供大家参考,具体内容如下
mainactivity:
public class sharedpreferencestestactivity extends activity implements view.onclicklistener{ private edittext edittext; private textview textview; private button write; private button read; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_shared_preferences_test); initview(); write.setonclicklistener(this); read.setonclicklistener(this); } private void initview() { edittext=(edittext)findviewbyid(r.id.edit_test); textview=(textview)findviewbyid(r.id.text_test); write=(button)findviewbyid(r.id.write); read=(button)findviewbyid(r.id.read); } @override public void onclick(view v) { switch (v.getid()){ case r.id.write: string some=edittext.gettext().tostring(); sharedpreferences pref = sharedpreferencestestactivity.this.getsharedpreferences("data",mode_private); sharedpreferences.editor editor = pref.edit(); editor.putstring("content",some); editor.commit(); toast.maketext(sharedpreferencestestactivity.this, "写入成功" , toast.length_long).show(); edittext.settext(""); break; case r.id.read: sharedpreferences pre = getsharedpreferences("data",mode_private); string name = pre.getstring("content",""); textview.settext(name); toast.maketext(sharedpreferencestestactivity.this, "读取成功" , toast.length_long).show(); break; } } }
mainactivity.xml
<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" tools:context="com.fae.mobile.testactivity.sharedpreferencestestactivity"> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <edittext android:textcolor="@color/red" android:background="@null" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/edit_test" android:layout_weight="1" /> <textview android:textcolor="@color/blue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/text_test" android:layout_weight="1"/> </linearlayout> <button android:layout_margintop="25dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/read" android:text="读"/> <button android:layout_margintop="25dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/write" android:text="写"/> </linearlayout>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。