android数据存储

 以复选和单选框为列:

    在回退之前,保存选项。

1、数据保存在File Explorer --> data -->data -->[

该项目的包](项目在虚拟机上运行之后,操作完毕返回

后,该项目的包内会自动生成文件)

xml文件

<CheckBox 
        android:id="@+id/cb1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="背景音乐"/>
         
     
     
     <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <RadioButton
           android:id="@+id/rb3"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content" 
           android:text="3格"/>
        <RadioButton
           android:id="@+id/rb6"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content" 
           android:text="6格"/>
     
        <RadioButton
           android:id="@+id/rb9"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content" 
           android:text="9格"/>
     </RadioGroup>





java代码


public class ProjActivity extends Activity{
     private CheckBox cb1;
     private RadioButton rb1;
     private RadioButton rb2;
     private RadioButton rb3;
     @Override
     public void onCreate(Bundle 

savedInstanceState){
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }

     @Override
     protected void onStart(){
          super.onStart();
          cb1 = (CheckBox)findViewById

(R.id.cb1);
          rb1 = (RadioButton)findViewById

(R.id.rb3);
          rb2 = (RadioButton)findViewById

(R.id.rb6);
          rb3 = (RadilButton)findViewById

(R.id.rb9);
          //获取选项数据存储
          SharedPreferences sp = 

getSharedPreferences

("setting",Context.MODE_PRIVATE);
          boolean music = sp.getBoolean

("music",true);
          cb1.setChecked(music);
     
          int grids = sp.getInt("grids",3);
          if(grids == 3)
             rb1.setChecked(true);
          else if(grids == 6)
             rb2.setChecked(true);
          else
             rb3.setChecked(true);
     }

     @Override
     protected void onStop(){
          super.onStop();
          //获取选项数据存储
          SharedPreferences sp = 

getSharedPreferences

("setting",Context.MODE_PRIVATE);
          //获取选项数据存储编辑器
          Editor editor = sp.edit();

          editor.putBoolean

("music",cb1.isChecker());
          if(rb1.isChecked()){
              editor.putInt("grids",3);
          }
          if(rb2.isChecked()){
              editor.putInt("grids",6);
          }
          if(rb3.isChecked()){
              editor.putInt("grids",9);
          }
          //提交数据
          editor.commit();
     }
}
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章