在ViewPager中的ListView片段中,只有在屏幕方向改变两次后才显示新值



在我的应用程序中,我有一个ViewPager与四个片段,其中一个包含一个ListView,我动态添加太在某些点使用更新方法,重新创建适配器。当片段第一次加载时,它完美地显示所有项目,但当我稍后做操作时,将视图添加到用于创建片段ListView适配器的列表中,新项目不显示(或删除)。有人知道为什么会这样吗?

带有ListView的Fragment:

public static class FavoritesFragment extends Fragment
{
    ListView list;
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        update();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View lv = inflater.inflate(R.layout.fragment_favorites, null);
        ListView list = (ListView) lv.findViewById(R.id.favorite_list);
        SeparatedListAdapter mAdapter = new SeparatedListAdapter(getActivity(), favoriteList); 
        list.setAdapter(mAdapter);
        return list;
    }
    public static FavoritesFragment newInstance(String text)
    {
        FavoritesFragment f = new FavoritesFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);
        f.setArguments(b);
        return f;
    }
}

更新方法:

public static void update() {
    favoriteList = new ArrayList<SeparatedListAdapter.Item>(); 
    sections = new ArrayList<String>();
    ListMultimap<String, JSONObject> listObjects = ArrayListMultimap.create();
    try {
        JSONObject obj = new JSONObject(loadJSONFromAsset(con));
        JSONArray m_jArry = obj.getJSONArray("Locations");
        for (int i = 0; i < m_jArry.length(); i++) 
          {
           JSONObject jo_inside = m_jArry.getJSONObject(i);
           if (favorites.contains(jo_inside.getString("Unique"))) 
           {
               listObjects.put(jo_inside.getString("Section"), jo_inside);
               if (!sections.contains(jo_inside.getString("Section"))) sections.add(jo_inside.getString("Section"));
           }
          }
        }
   catch (JSONException e)
   {
       e.printStackTrace();
   }
    for (String s : sections)
    {
        favoriteList.add(new SeparatedListAdapter.SectionItem(s));
        List<JSONObject> objectsInSection = listObjects.get(s);
        for (JSONObject j : objectsInSection)
        {
            try {
            favoriteList.add(new SeparatedListAdapter.EntryItem(j.getString("name");
            }
            catch (JSONException e)
            {
            }
        }
    }
}

当使用ListView将页面更改为Fragment时:

View vc = mPager.findViewWithTag("favorites");
                        if (vc != null) {
                            ListView lv = (ListView) vc.findViewById(R.id.favorite_list);
                            update();
                            lv.setAdapter(new SeparatedListAdapter(MainActivity.this, favoriteList));
                            }

很抱歉写了这么长一篇文章,但任何帮助都会非常感激:)

你试过调用这个吗:

让mAdapter成为一个实例变量,而不是在onCreateView

中实例化它
mAdapter.notifyDataSetChanged();

编辑:::

如果你做了这样的事情会怎么样?

mAdapter.clear();
mAdapter.addAll(favoriteList);

最新更新