使用SharedPreferences保存EditText中的内容

来源:互联网 发布:韩语电影翻译软件 编辑:程序博客网 时间:2024/06/09 14:06

前些日子一直忙着问SharedPrefences的用法,发现网上大多数都是用来保存用户名和密码,虽然可以借鉴,但有源码更简单明了一些,特在此记录。

做了个note,xml全局EditText覆盖,退出即保存,无保存按钮,无退出按钮,用SharedPreferences。

下面是源码:

MainActivity.java

package com.example.note;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.widget.EditText;import android.content.SharedPreferences;public class MainActivity extends Activity {private EditText myEditText;private static final String TEMP_INFO="temp_info";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);myEditText = (EditText)findViewById(R.id.text001);SharedPreferences sp = getSharedPreferences(TEMP_INFO,MODE_WORLD_READABLE);String content = sp.getString("info_content", "");myEditText.setText(content);}protected void onStop(){super.onStop();SharedPreferences.Editor editor = getSharedPreferences(TEMP_INFO,MODE_WORLD_WRITEABLE).edit();editor.putString("info_content", myEditText.getText().toString());editor.commit();}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.activity_main, menu);return true;}}






activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <EditText        android:id="@+id/text001"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="#666666"        android:gravity="top"/></RelativeLayout>






AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.note"    android:versionCode="1"    android:versionName="1.0" >
    <uses-sdk        android:minSdkVersion="12"        android:targetSdkVersion="16" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.note.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>





0 0
原创粉丝点击