package com.example.sharepreferen; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends ActionBarActivity implements OnClickListener{ private Button btnSave; private EditText etContent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnSave = (Button)findViewById(R.id.btn_save); etContent = (EditText)findViewById(R.id.et_content); //得到SharedPreferences取值 SharedPreferences preferences = this.getSharedPreferences("config", Context.MODE_PRIVATE); String content = preferences.getString("content", ""); if (!content.trim().equals("")) { etContent.setText(content); } btnSave.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_save: save(etContent.getText().toString()); break; default: break; } } public void save(String content) { //获得SharedPreferences 并进行编辑 SharedPreferences preferences = this.getSharedPreferences("config", Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putString("content", content); //记住一定要提交 editor.commit(); Toast.makeText(this, "保存成功", 0).show(); } }
手机中的一些设置信息都是保存在其中的。