添加后,notifyDataSetChanged()无法正常工作

时间:2016-06-23 14:27:40

标签: android listview android-adapter

这种情况经常发生,但我真的不知道该怎么做。

这是片段中的代码:

公共类MainFragment扩展了Fragment {

private ListView listView;
private static TicketsAdapter ticketsAdapter;
private static ArrayList<Ticket> tickets = new ArrayList<Ticket>();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_main, container, false);

    listView = (ListView) view.findViewById(R.id.list_tickets);        
    ticketsAdapter = new TicketsAdapter(tickets);
    listView.setAdapter(ticketsAdapter);

    return view;
}
public static void addTicket(Ticket ticket){
    tickets.add(ticket);
    ticketsAdapter.notifyDataSetChanged();
    Log.d(A.TAG,"tickets =" + tickets.size());
}

}

现在,日志显示票数增加,但ListView未更新

这是适配器:

public class TicketsAdapter extends BaseAdapter {

    private ArrayList<Ticket> tickets = new ArrayList<Ticket>();
    private LayoutInflater lInflater;
    private ViewHolder viewHolder;

    public TicketsAdapter(ArrayList<Ticket> tickets){
        this.tickets.clear();
        this.tickets.addAll(tickets);
        lInflater = (LayoutInflater) MainActivity.getActivity()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null){
            convertView = lInflater.inflate(R.layout.list_item, parent, false);
            viewHolder = new ViewHolder();

            //finding views etc

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }       
        Ticket ticket = (Ticket) getItem(position);

         //Showing data on views

        return convertView;
    }

    @Override
    public int getCount() {
        return tickets.size();
    }

    @Override
    public Object getItem(int position) {
        return tickets.get(position);
    }

    @Override
    public long getItemId(int position) {
        return Long.parseLong(tickets.get(position).getId());
    };

    static class ViewHolder{
        //bunch of views
    }
}

1 个答案:

答案 0 :(得分:1)

您正在适配器中创建一个新列表,只是将片段列表中的项目添加到其中。适配器中的列表没有引用片段中的列表(因为它是一个新列表),因此您的适配器无法知道外部列表中的更改。

您可以执行以下操作:

    private ArrayList<Ticket> tickets;
    private LayoutInflater lInflater;
    private ViewHolder viewHolder;

    public TicketsAdapter(ArrayList<Ticket> tickets) {
        this.tickets = tickets;
        lInflater = (LayoutInflater) MainActivity.getActivity()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

如果您这样做,您的适配器将引用来自您的片段的相同列表(因为您没有发送新列表,但是对片段类中的列表的引用)以及片段中所做的更改一旦您拨打notifyDataSetChanged(),我们就会在您的适配器中反映出来。

希望这会有所帮助。 =)