我在活动创建一个对话框onCreateDialog
方法这样如何处理托管选项菜单对话框中的listView项目更改?
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, android.R.id.text1, items);
dialog = new AlertDialog.Builder(this).setTitle(R.string.dialogTitle).setAdapter(adapter,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
// do something
}
}).create();
我想在对话框中显示的项目是在一个简单的ArrayList
private List<String> items = new ArrayList<String>();
对话框现在管理(保存和恢复)通过我的活动 - 据我所知。因此,每次用户按下菜单按钮打开对话框时都不会重新创建。
根据某些用户对活动的选择 - 对话框的项目列表需要更改。我认为这将是没有太大的问题,但改变列表的内容后,我遇到以下异常:
06-03 10:55:29.263: ERROR/AndroidRuntime(276): java.lang.IllegalStateException:
The content of the adapter has changed but ListView did not receive a notification.
Make sure the content of your adapter is not modified from a background thread,
but only from the UI thread. [in ListView(16908785, class com.android.internal.app.AlertController$RecycleListView) with Adapter(class android.widget.ArrayAdapter)]
我调试的Thread.currentThread().getId()
,发现它始终为“1”(对话的建立,也更改物品清单)。
如何处理项目列表更改以便通过我的对话框发现?或者我应该避免使用“托管”对话框,并在用户每次打开它时从头开始创建它?
我该怎么做/应该让事情有效?
感谢您的任何建议!
我不暂停活动 - 所以我没有通过'onSaveInstanceState' /'onRestoreInstanceState'。用户只需在活动中选择一个不同的_parent_项目,并且我需要在选项菜单对话框中显示不同的_child_项目列表。此刻,我为对话框ListView创建了一个新的“适配器”,并通过'onPrepareDialog'中的ListView传递它。所以我不必创建一个新的对话框 - 但我认为现有的Adapter本身应该已经注意到数据更改并通知ListView。不过谢谢你的回应。 – FrVaBe 2011-06-03 09:52:58
我明白了,我被提到“保存和恢复”的句子弄糊涂了。我很确定这个对话框在主UI线程中运行,这个错误信息会误导IMO。你有'ArrayAdapter.setNotifyOnChange()'设置为true,或者在数据改变后正确调用'Adapter.notifyDataSetChanged()'?如果这个问题持续存在,我会亲自尝试一个自定义的'Adapter',通过继承'BaseAdapter'。这很容易,更灵活,并且会避免一些'ArrayAdapter'“魔术”。 – olivierg 2011-06-03 12:53:12
'ArrayAdapter.setNotifyOnChange()'和'Adapter.notifyDataSetChanged()'做了我一直在寻找的东西。如果你更新你的答案,我会接受它!感谢你的支持! – FrVaBe 2011-06-03 14:34:11