Shareprefrence

Xml文件

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:orientation="vertical"
 5     android:id="@+id/activity_main"
 6     android:layout_width="match_parent"
 7     android:layout_height="match_parent"
 8     android:paddingBottom="@dimen/activity_vertical_margin"
 9     android:paddingLeft="@dimen/activity_horizontal_margin"
10     android:paddingRight="@dimen/activity_horizontal_margin"
11     android:paddingTop="@dimen/activity_vertical_margin"
12     tools:context="sharedpreference.zhangmeng.com.sharedpreference.MainActivity">
13 
14     <EditText
15         android:id="@+id/et"
16         android:layout_width="match_parent"
17         android:layout_height="wrap_content"
18          />
19     <Button
20         android:id="@+id/bt_saveData"
21         android:text="save data"
22         android:layout_width="match_parent"
23         android:layout_height="wrap_content" />
24     <Button
25         android:id="@+id/bt_readData"
26         android:layout_width="match_parent"
27         android:layout_height="wrap_content"
28         android:text="read text"/>
29 </LinearLayout>

MainActivity

 1 package sharedpreference.zhangmeng.com.sharedpreference;
 2 
 3 import android.content.SharedPreferences;
 4 import android.support.v7.app.AppCompatActivity;
 5 import android.os.Bundle;
 6 import android.view.View;
 7 import android.widget.EditText;
 8 import android.widget.Toast;
 9 
10 public class MainActivity extends AppCompatActivity {
11 
12 private EditText et=null;
13     private SharedPreferences.Editor editor=null;
14 
15     @Override
16     protected void onCreate(Bundle savedInstanceState) {
17         super.onCreate(savedInstanceState);
18         setContentView(R.layout.activity_main);
19         et=(EditText)findViewById(R.id.et);
20         findViewById(R.id.bt_saveData).setOnClickListener(new View.OnClickListener() {
21             @Override
22             public void onClick(View v) {
23                 editor=getSharedPreferences("data",MODE_PRIVATE).edit();
24                 editor.putString("name",et.getText().toString());
25                 editor.commit();
26                 Toast.makeText(getApplicationContext(),"The data saved.",Toast.LENGTH_LONG).show();
27             }
28         });
29 
30         findViewById(R.id.bt_readData).setOnClickListener(new View.OnClickListener() {
31             @Override
32             public void onClick(View v) {
33                 SharedPreferences pref=getSharedPreferences("data",MODE_PRIVATE);
34 
35                 Toast.makeText(getApplicationContext(),pref.getString("name",""),Toast.LENGTH_LONG).show();
36             }
37         });
38     }
39 }

 

posted on 2016-10-01 14:58  ITGiant  阅读(169)  评论(0编辑  收藏  举报

导航