.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.hanqi.application3.DataActivity1" android:orientation="vertical"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/et_1" android:hint="Key"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/et_2" android:hint="Value"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:text="保存" android:layout_weight="1" android:onClick="bt1_onClick"/> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:text="读取" android:layout_weight="1" android:onClick="bt2_onClick"/> </LinearLayout> </LinearLayout>
.java
package com.hanqi.application3; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class DataActivity1 extends AppCompatActivity { EditText et1; EditText et2; SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_data1); et1=(EditText)findViewById(R.id.et_1); et2=(EditText)findViewById(R.id.et_2); //1.获取sp的实例,制定了文件名和操作模式 sp = getSharedPreferences("mydata",MODE_PRIVATE); } //保存 public void bt1_onClick(View v) { //1.获取Key和Value String key = et1.getText().toString(); String value = et2.getText().toString(); if (key.length() ==0||value.length() == 0) { Toast.makeText(DataActivity1.this, "key或value不能为空", Toast.LENGTH_SHORT).show(); } else { //2.取得Editor edit编辑器 SharedPreferences.Editor editor = sp.edit(); //3.放入键值对 editor.putString(key,value); //4.提交保存 boolean b = editor.commit(); if (b) { Toast.makeText(DataActivity1.this, "保存成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(DataActivity1.this, "保存失败", Toast.LENGTH_SHORT).show(); } } } //读取 public void bt2_onClick(View v) { //1.获取要读的key String key = et1.getText().toString(); //2.读并设置文本框 et2.setText(sp.getString(key,"没有发现key")); } }
时间: 2024-10-29 19:10:02