更新时ListFragment重叠

时间:2014-11-14 11:00:58

标签: android android-listfragment

我点击NavigationDrawer后,尝试刷新我的CustomListFragment,它在两个窗格布局中从ListFragment延伸:

public void updateInputView(String date)
{
    ArrayList<Custom> values;
    DataSource ds = new DataSource(this.getActivity());

    ds.openReadOnly();
    values = ds.getValues(date);
    ds.close();

    CustomAdapter adapter = new CustomAdapter(this.getActivity(), values);

    adapter.notifyDataSetChanged();
    setListAdapter(adapter);
}

调用updateInputView后,第二个列表与启动时创建的第一个列表重叠。现在当我在NavigationDrawer中选择另一个时,第二个列表消失,第三个列表再次与第一个列表重叠。

那么这里有什么问题?

编辑:

private void createView()
{
    String  date;

    if (sDate == null)
    {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        date = dateFormat.format(cal.getTime());
    }
    else
    {
        date=sDate;
    }

    DataSource ds = new DataSource(this.getActivity());

    ds.openReadOnly();
    values = ds.getValues(date);
    ds.close();

    updateInputView(date);

}

这是之前的代码。

后:

public void updateInputView(String date)
{


    DataSource ds = new DataSource(this.getActivity());

    ds.openReadOnly();
    values = ds.getValues(date);
    ds.close();


    this.getActivity().setTitle(this.getResources().getString(R.string.app_name)+" "+ds.toPrettyDate(date));
    adapter.notifyDataSetChanged();

    //setListAdapter(adapter);
}


private void createView()
{
    String  date;

    if (sDate == null)
    {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        date = dateFormat.format(cal.getTime());
    }
    else
    {
        date=sDate;
    }

    DataSource ds = new DataSource(this.getActivity());

    ds.openReadOnly();
    values = ds.getValues(date);
    ds.close();

    this.getActivity().setTitle(this.getResources().getString(R.string.app_name)+" "+ds.toPrettyDate(date));    
adapter = new CustomAdapter(this.getActivity(), values);
    setListAdapter(adapter);

}

1 个答案:

答案 0 :(得分:0)

您只需拨打setListAdapter(adapter);一次。要更新列表,请致电adapter.notifyDataSetChanged();

public class Mainactivity extends ListFragment {
    CustomAdapter adapter ;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
       // Your code .....
       if(adapter ==null){
           adapter = new CustomAdapter(this.getActivity(), values);
           setListAdapter(adapter);
       } 
    }


    public void updateInputView(String date)
    {
        ArrayList<Custom> values;
        DataSource ds = new DataSource(this.getActivity());

        ds.openReadOnly();
        values = ds.getValues(date);
        ds.close();

        if(adapter!=null){
            adapter.notifyDataSetChanged();
      }
   }
}

P.S:确保只调用onCreateView一次。

希望它会帮助你ツ