如何永久保存列表视图中的复选框状态?

时间:2012-02-18 09:34:24

标签: android listview checkbox

我有一个带复选框的自定义列表视图。我希望在应用程序的整个生命周期中保存复选框的状态。我怎样才能做到这一点?谢谢

2 个答案:

答案 0 :(得分:2)

SharedPreferences类提供了一个通用框架,允许您保存和检索原始数据类型的持久键值对。

为了完整起见,我在此处提供示例代码。

public class Xxx extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";

@Override
protected void onCreate(Bundle state){
   super.onCreate(state);
   . . .

   // Restore preferences
   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   boolean silent = settings.getBoolean("silentMode", false);
   setSilent(silent);
}

@Override
protected void onStop(){
   super.onStop();

  // We need an Editor object to make preference changes.
  // All objects are from android.context.Context
  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putBoolean("silentMode", mSilentMode);

  // Commit the edits!
  editor.commit();
}

}

答案 1 :(得分:0)

你不应该在ListView中使用复选框,我更喜欢使用TableLayout。 但是,如果要使用ListView,请考虑以下先前的问题: -

Android save Checkbox State in ListView with Cursor Adapter

Finding the Checked state of checkbox in a custom listview

Code does not extend ListViewActivity, but does have a listview

关于同一主题还有很多其他问题,请考虑搜索它们。

编辑:动态TableLayout替换ListView

的示例

XML: -

<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout
 android:id="@+id/table"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</TableLayout>
</ScrollView>

Java中的代码摘录: -

TableLayout table=(TableLayout)findViewByid(R.id.table);
ArrayList<CheckBox> cbData=new ArrayList<CheckBox>();
for(int i=0;i<rowCount;i++){
    TextView t1=new TextView(this);
    t1.setText("Text1");
    TextView t2=new TextView(this);
    t2.setText("Text2");
    CheckBox cb=new CheckBox(this);
    TableRow row=new TableRow(this);
    row.addView(t1);
    row.addView(t2);
    row.addView(cb);
    cbData.add(cb);
    table.addView(row);
}

使用上面的代码,您可以在TableLayout中添加所需的行,并且由于TableLayout不会回收它的视图,因此您不必缓存复选框数据和状态。要访问CheckBoxes,您可以使用cbData.get(index)方法。比编码缓存复选框状态容易得多。

相关问题