8.1 Android Basic 数据存储 Preferences SharedPreferences Demo2

Source code

SharePreferences Demo2

   

  • 新建项目PreferDemo, 编辑res/layout/main.xml布局文件:

    <?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">

    <CheckBox android:text="This checkbox is: unchecked"

    android:id="@+id/check"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"></CheckBox>

    <Button android:text="Close"

    android:id="@+id/close"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"></Button>

    </LinearLayout>

    2. 编辑PreferDemo类,按如下代码修改:

    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.CompoundButton.OnCheckedChangeListener;

       

    public class PrefsDemo extends Activity {

    /** Called when the activity is first created. */

    private CheckBox cb;

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    cb = (CheckBox)findViewById(R.id.check);

    cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    // TODO Auto-generated method stub

    if(isChecked){

    cb.setText("CheckBox是选中的");

    }else{

    cb.setText("CheckBox没有选中");

    }

    }

    });

    Button btn = (Button)findViewById(R.id.close);

    btn.setOnClickListener(new Button.OnClickListener(){

    @Override

    public void onClick(View v) {

    // TODO Auto-generated method stub

    finish();

    }

    });

    }

       

    @Override

    protected void onPause() {

    // TODO Auto-generated method stub

    super.onPause();

    SharedPreferences settings = getPreferences(0);

    SharedPreferences.Editor editor = settings.edit();

    editor.putBoolean("cb_checked", cb.isChecked());

    editor.commit();

    }

       

    @Override

    protected void onResume() {

    // TODO Auto-generated method stub

    super.onResume();

    SharedPreferences settings = getPreferences(0);

    cb.setChecked(settings.getBoolean("cb_checked", false));

    }

    }

       

    在onPause()方法中使用getPreferences()方法获取 SharedPreferences对象。使用SharedPreferences.Editor.edit()方法打开编辑状态,将checkbox的状态使用putBoolean()方法写入。 最后使用commit()方法提交。

    在onResume()方法中获取写入的值。

       

    im@xingquan.org

posted @ 2011-03-25 17:18  敏捷学院  阅读(191)  评论(0编辑  收藏  举报