Android開發 基本「共用偏好設定」範例

參考來源:Android Developers 訓練課程 儲存索引鍵值組

建立基本畫面配置

畫面配置

對應的寫入程式碼

    public void buttonSaveClick(View view){
        String a = ((EditText)findViewById(R.id.editText)).getText().toString();
        int b = Integer.parseInt(((EditText) findViewById(R.id.editText2)).getText().toString());

        SharedPreferences sp = this.getPreferences( this.MODE_PRIVATE );
        SharedPreferences.Editor spe = sp.edit();
        spe.putString( "to.fili.testpref.ooxxoioi.sss", a );
        spe.putInt( "to.fili.testpref.ooxxoioi.ddd", b );
        spe.commit();
    }
`</pre>

### 對應的讀取程式碼

<pre>`    public void buttonLodClick(View view){
        SharedPreferences sp = this.getPreferences( this.MODE_PRIVATE );
        String a = sp.getString("to.fili.testpref.ooxxoioi.sss", "nothing");
        int b = sp.getInt("to.fili.testpref.ooxxoioi.ddd", 0);

        ((TextView)findViewById(R.id.textView)).setText( a );
        ((TextView)findViewById(R.id.textView2)).setText( String.valueOf(b) );
    }