須要一個文本框和輸入框(輸入你要存放的數據)並且須要在對應JAVA文件中獲取控件,這裏只提出一下不寫了,主要由於都是基礎代碼,貼出來浪費時間。java
主要是隻貼出關鍵代碼,設置了3個按鈕分別是實現寫入,讀取以及清空的功能以下:android
一個是android:onClick="save"app
一個是android:onClick="read"ide
一個是android:onClick="clear"spa
雙引號內可自定義,主要是實如今JAVA內實現3個按鈕的監聽,不用寫很長串的監聽代碼,上面的定義只是個人我的習慣而已,常規命名勿噴勿吐槽哈哈哈。code
首先要獲取文本框和輸入框控件而且分別命名爲text_dengji和edit_thing。blog
以及實現了對APP進入的次數進行計數的小功能。get
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_dengji =(TextView) findViewById(R.id.text_dengji);
edit_thing =(EditText) findViewById(R.id.edit_thing);
//進行讀取或者寫操做,爲默認操做模式,表明該文件是私有數據,只能被應用自己訪問,
// 在該模式下,寫入的內容會覆蓋原文件的內容,若是想把新寫入的內容追加到原文件中
sharedPreferences = getSharedPreferences("yxl", MODE_PRIVATE);
editor = sharedPreferences.edit();
//實現進入app次數的統計
test = getSharedPreferences("test", MODE_PRIVATE);
SharedPreferences.Editor edit = test.edit();
int count = test.getInt("count", 1);
Toast.makeText(getApplicationContext(),"訪問了"+ count +"次",Toast.LENGTH_SHORT).show();
edit.putInt("count",++count);
edit.commit();
}
實現對3個按鈕的監聽方法。string
public void save(View view){
editor.putString("001", edit_thing.getText().toString()); //寫入當前輸入的數據
editor.commit();
}
public void read(View view){
String string = sharedPreferences.getString("001", ""); //獲取當前存的數據
text_dengji.setText(string);
}
public void clear(View view){
editor.clear(); //清除當前數據
editor.commit();
}