本文写了一个安卓应用程序,实现多个checkbox勾选,下次打开时可以记住上次勾选的状态。用setOnCheckedChangeListener来做事件响应,用SharedPreferences来存储。代码如下:
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"
>
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="你是谁:"
/>
<CheckBox
android:id="@+id/shuaige"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="帅哥"
/>
<CheckBox
android:id="@+id/meinv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="美女"
/>
<CheckBox
android:id="@+id/ptr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="普通人"
/>
</LinearLayout>
package com.example.checkboxsj;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
public class MainActivity extends Activity implements OnCheckedChangeListener {
/** Called when the activity is first created. */
//对控件对象进行声明
CheckBox a;
CheckBox b;
CheckBox c;
EditText editText1=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//通过控件的ID来得到代表控件的对象
a=(CheckBox)findViewById(R.id.shuaige);
b=(CheckBox)findViewById(R.id.meinv);
c=(CheckBox)findViewById(R.id.ptr);
editText1=(EditText)findViewById(R.id.editText1);
a.setOnCheckedChangeListener(this);
b.setOnCheckedChangeListener(this);
c.setOnCheckedChangeListener(this);
//设置初始状态
SharedPreferences sp=this.getSharedPreferences("box",Context.MODE_PRIVATE);
boolean an1=sp.getBoolean("b1", false );
a.setChecked(an1);
boolean an2=sp.getBoolean("b2", false );
b.setChecked(an2);
boolean an3=sp.getBoolean("b3", false );
c.setChecked(an3);
//给CheckBox设置事件监听
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
SharedPreferences sp=getSharedPreferences("box",MODE_PRIVATE);
Editor e=sp.edit();
switch(buttonView.getId()){
case R.id.shuaige :
e.putBoolean("b1", isChecked);break;
case R.id.meinv :
e.putBoolean("b2", isChecked);break;
case R.id.ptr:
e.putBoolean("b3", isChecked);break;
}
e.commit();
}
}
如图: