需求:打开应用的时候读取原先已经设置的好内容,点击保存按钮的时候修改原先的内容,再次打开显示新设置的内容
这个配置的xml文件位于 /data/data/应用所在包名/shared_prefs/下
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名" />
<EditText
android:id="@+id/nameET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="电话" />
<EditText
android:id="@+id/phoneET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="邮箱" />
<EditText
android:id="@+id/emailET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress" />
<Button
android:onClick="onClick"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存为默认" />
</LinearLayout>
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText nameET;
private EditText phoneET;
private EditText emailET;
private SharedPreferences sp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nameET = (EditText) findViewById(R.id.nameET);
phoneET = (EditText) findViewById(R.id.phoneET);
emailET = (EditText) findViewById(R.id.emailET);
/**
* 第一个参数是文件名,不需要手动加.xml后缀,系统会自动加。 例如这个文件名就叫config.xml
* 第二个参数是,模式
*/
sp = getSharedPreferences("config", MODE_PRIVATE);//获取对象,默认指向当前应用所在文件夹
//sp = getPreferences(MODE_PRIVATE); 如果用这个方法获取SharedPreferences,那么文件名默认是当前类名MainActivity
nameET.setText(sp.getString("name", ""));//获取数据 sp.getString()第一个参数是要获取数据的参数名,第二个参数是,如果不存在这个参数名,显示的默认值
phoneET.setText(sp.getString("phone", ""));
emailET.setText(sp.getString("email", ""));
}
public void onClick(View view){
String name = nameET.getText().toString();
String phone = phoneET.getText().toString();
String email = emailET.getText().toString();
Editor editor = sp.edit();//获取一个编辑器对象
editor.putString("name", name);//存储数据,还未进入文件
editor.putString("phone", phone);
editor.putString("email", email);
editor.commit();//提交修改(类似事务)
Toast.makeText(getApplicationContext(), "设置成功", Toast.LENGTH_SHORT).show();
}
}