【发布时间】:2012-02-19 00:16:34
【问题描述】:
我有一个带有复选框的自定义列表视图。我希望在应用程序的整个生命周期中保存复选框的状态。我怎样才能做到这一点?谢谢你
【问题讨论】:
-
这样你的问题无法回答。请提供更多信息。比如你显示的数据来自哪里。如果它是一个 sqlite 数据库,则将状态存储在您的数据库中。如果您的数据是从服务器解析...
-
复选框由用户选中,不受任何其他服务的影响。
我有一个带有复选框的自定义列表视图。我希望在应用程序的整个生命周期中保存复选框的状态。我怎样才能做到这一点?谢谢你
【问题讨论】:
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();
}
}
【讨论】:
您不应该在 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) 方法。比缓存复选框状态的编码要容易得多。
【讨论】: