1.XML檔案中
需要一個文本框和輸入框(輸入你要存放的資料)而且需要在對應JAVA檔案中獲取控制元件,這里只提出一下不寫了,主要因為都是基礎代碼,貼出來浪費時間,
主要是只貼出關鍵代碼,設定了3個按鈕分別是實作寫入,讀取以及清空的功能如下:
一個是android:onClick="save"
一個是android:onClick="read"
一個是android:onClick="clear"
雙引號內可自定義,主要是實作在JAVA內實作3個按鈕的監聽,不用寫很長串的監聽代碼,上面的定義只是我的個人習慣而已,常規命名勿噴勿吐槽哈哈哈,
2.主界面.java
首先要獲取文本框和輸入框控制元件并且分別命名為text_dengji和edit_thing,
以及實作了對APP進入的次數進行計數的小功能,
@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個按鈕的監聽方法,
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();
}
個人APP實作效果圖


轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/11383.html
標籤:Android
