安卓:屏幕旋转后listview出现重复条目

4

我有一个listView,它在onCreate()中填充数据,由于屏幕旋转会再次调用onCreate(),因此它会再次填充数据,这样每次旋转后就会添加条目,而我不想要这样。onCreate()基本上是这样的:

@Override
public void onActivityCreated(Bundle savedInstanceState) 
{
    super.onActivityCreated(savedInstanceState);
    myList = new ArrayList<SingleEntry>();
    new getList().execute(); //Async task to fill myList

    ListView lv = (ListView) getActivity().findViewById(R.id.ListView01);

    itemAdapter = new ItemAdapterOverview(getActivity().getApplicationContext(), myList);


    lv.setAdapter(itemAdapter);
}

其中 myList 是一个类变量的 ArrayList。在填充之前,我尝试在 onCreate() 中设置一个空的 adapter,这是 Google 建议我的。但它没有起作用。


那么如果您向右旋转手机,您需要保持数组吗? - Nikunj Patel
3个回答

2
在您的清单活动中添加以下内容:
android:configChanges="orientation|keyboardHidden|screenSize"

并且要覆盖你的活动中的OnConfigurationChanged方法,就像这样:

@Override
public void onConfigurationChanged(Configuration newConfig) {
}

这不应该再调用您的onCreate了。

1

您可以在Android的方法onSaveInstanceState中保存myList,类似于以下方式:

protected void onSaveInstanceState(Bundle bundle) {
    bundle.putSerializable("myList", myList);
    super.onSaveInstanceState(bundle);
}

请确保将类SingleEntry实现Serializable接口,使其成为可序列化的(注意:如果您在SingleEntry类内部有任何复杂的数据结构,则还应该使它们实现Serializable接口)。然后在您的onCreate中,您可以使用类似以下代码:

@Override
public void onActivityCreated(Bundle savedInstanceState) 
{
    super.onActivityCreated(savedInstanceState);

    if(savedInstanceState != null) { //Check if the save instance state is not null

       //If is not null, retrieve the saved values of the myList variable
       myList = (ArrayList<SingleEntry>) savedInstanceState.getSerializable("myList");

       ListView lv = (ListView) getActivity().findViewById(R.id.ListView01);

       itemAdapter = new ItemAdapterOverview(getActivity().getApplicationContext(), myList);

       lv.setAdapter(itemAdapter);
    }
    else { //Bundle is empty so you should intialize the myList variable
       myList = new ArrayList<SingleEntry>();
       new getList().execute(); //Async task to fill myList

       ListView lv = (ListView) getActivity().findViewById(R.id.ListView01);

       itemAdapter = new ItemAdapterOverview(getActivity().getApplicationContext(), myList);


       lv.setAdapter(itemAdapter);
    }
}

1

简单的“快速修复”答案: 在onCreate()中调用.clear()方法清除itemAdapter,您也可以尝试在列表适配器上调用.notifyDataSetChanged()。

这将在再次添加它们之前清除适配器中的项目。

不太简单但更完整的答案: 另一种方法是在onCreate()中通过bundle传递itemAdapter,请参阅“在配置更改期间保留对象”部分http://developer.android.com/guide/topics/resources/runtime-changes.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接