【发布时间】:2014-05-27 17:36:57
【问题描述】:
我的MainActivity 包含一个ListView 和一个启动DetailsActivity 的菜单项。 DetailsActivity 可以将项目添加到填充ListView 的数据库中。以下是对我造成问题的用例的描述:
- 开始
MainActivity。 - 检查列表中的一些项目。
- 启动
DetailsActivity。 - 将项目添加到数据库中。
- 按返回键返回
MainActivity。
在此序列结束时,步骤 2 中的任何检查都不会保留,即使我尝试恢复它们的状态。
MainActivity.onPause() 和 MainActivity.onResume():
@Override
public void onPause() {
super.onPause();
this.savedSelection = this.adapter.getSelection();
}
@Override
public void onResume() {
super.onResume();
// restore default header state
CheckedTextView headerCheck = (CheckedTextView) this.headerView
.findViewById(R.id.checkmark);
headerCheck.setChecked(false);
boolean[] newSelection = new boolean[this.adapter.getCount()];
if (this.savedSelection != null) {
// copy old selection array into new selection array
int numSelected = 0;
for (int i = 0; i < this.savedSelection.length; i++) {
newSelection[i] = this.savedSelection[i];
if (newSelection[i]) {
numSelected++;
}
View row = this.listView.getChildAt(i + 1);
if (row != null) {
CheckedTextView checkbox = (CheckedTextView) row
.findViewById(R.id.checkmark);
checkbox.setChecked(newSelection[i]);
TextView playerText = (TextView) row
.findViewById(R.id.player_name_text_view);
Log.d(TAG, playerText.getText().toString() + " checked? "
+ checkbox.isChecked());
}
}
// restore header state
if (numSelected == newSelection.length) {
headerCheck.setChecked(true);
}
}
// restore state
this.adapter.setSelection(newSelection);
}
MyAdapter.getView():
public View getView(final int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
CheckedTextView ctv = (CheckedTextView) v.findViewById(R.id.checkmark);
final Activity curActivity = (Activity) this.context;
// restore selection
if (this.selection != null) {
ctv.setChecked(this.selection[position]);
}
// set listener
ctv.setOnClickListener(new OnClickListener() {
@SuppressLint("NewApi")
@Override
public void onClick(View v) {
CheckedTextView cview = (CheckedTextView) v
.findViewById(R.id.checkmark);
cview.toggle();
BaseballCardAdapter.this.selection[position] = cview
.isChecked();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
curActivity.invalidateOptionsMenu();
}
}
});
return v;
}
【问题讨论】:
-
您可以添加您在适配器中使用的“getView”代码吗?