2011年2月9日星期三

Android的共享選項編輯器(SharedPreferences.Editor)

共享選項編輯器(SharedPreferences.Editor)是一個用於修改SharedPreferences對象值的接口. 編輯選項值後, 調用commit()或apply()方法以更新SharedPreferences.

Android的共享選項編輯器(SharedPreferences.Editor)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<CheckBox
android:id="@+id/pref_checkbox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/pref_edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/saveedittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save EditText"
/>
</LinearLayout>


package com.AndroidSharedPreferencesEditor;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

public class AndroidSharedPreferencesEditor extends Activity {

CheckBox checkBox;
EditText editText;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkBox = (CheckBox)findViewById(R.id.pref_checkbox);
editText = (EditText)findViewById(R.id.pref_edittext);
Button buttonSaveEditText = (Button)findViewById(R.id.saveedittext);
LoadPreferences();

checkBox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){

@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
SavePref();
}});

buttonSaveEditText.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePref();
}});

}

private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);

boolean savedBoolean = sharedPreferences.getBoolean("PREF_BOOLEAN", false);
String savedString = sharedPreferences.getString("PREF_STRING", "");

checkBox.setChecked(savedBoolean);
editText.setText(savedString);
}

private void SavePref(){
boolean booleanCheckBox = checkBox.isChecked();
String stringEditText = editText.getText().toString();

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("PREF_BOOLEAN", booleanCheckBox);
editor.putString("PREF_STRING", stringEditText);
editor.commit();
}
}



相關文章:
- getPreferences() vs getSharedPreferences()

沒有留言:

發佈留言