RecyclerView notifyDatasetChanged无效

时间:2017-02-07 11:40:34

标签: android android-recyclerview

RecyclerView内的FragmentActivity。我需要从RecyclerView刷新Activity。我在Fragment内添加了一个名为notifyDatasetChanged的方法来刷新RecyclerView。但是notifyDatasetChanged没有用。

这是我的Fragment

public class CategoryFragment extends Fragment{
private  RecyclerView recyclerView;
private  EventsAdapter adapter;
static Context context = null;
private  List<Category> categories;
private  List<Item> allItems = new ArrayList();
private ReminderDatabase dbHandler;

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

    if(!checkDatabase()){
        copyDatabase();
    }
    context = getActivity();

    dbHandler = new ReminderDatabase(context);
    fillAllItems();
}

public void fillAllItems(){
    categories = dbHandler.getAllCategory();
    for(int i=0;i<categories.size();i++){
        Category category = categories.get(i);
        Item categoryItem = new Item(category.getTitle(),category.getColor(),Category.CATEGORY_TYPE);
        allItems.add(categoryItem);
        List<Event> events = dbHandler.getEventsByCategory(category.getTitle());
        for(int j=0;j<events.size();j++){
            Event e = events.get(j);
            Item eventItem = new Item(e.getId(),e.getTitle(),e.getDescription(),e.getPlace(),e.getCategory(),e.getTime(),e.getDate(),categoryItem.getColor(),e.isShow(),Event.EVENT_TYPE);
            allItems.add(eventItem);
        }
    }
}



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.category_fragment, container, false);
    recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
    adapter = new EventsAdapter(getContext(),allItems);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(adapter);

    return v;
}

public boolean checkDatabase(){
    String path = "/data/data/com.example.materialdesign.reminder/databases/";
    String filename = "Remind";
    File file = new File(path+filename);
    Log.d("Database","File exists -> "+file.exists());
    return file.exists();
}

public void copyDatabase(){
    String path = "/data/data/com.example.materialdesign.reminder/databases/Remind";
    ReminderDatabase dbHandler = new ReminderDatabase(getContext());
    dbHandler.getWritableDatabase();
    InputStream fin;
    OutputStream fout;
    byte[] bytes = new byte[1024];
    try {
        fin = getActivity().getAssets().open("Remind");
        fout = new FileOutputStream(path);
        int length=0;
        while((length = fin.read(bytes))>0){
            fout.write(bytes,0,length);
        }
        fout.flush();
        fout.close();
        fin.close();
        Log.d("Database","successfully copied database");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.d("Database","-Error" +e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        Log.d("Database","-Error" +e.getMessage());
    }
}

@Override
public void onResume() {
    super.onResume();
    allItems.clear();
    Log.d("TAG","onresume");
    fillAllItems();
    adapter.notifyDataSetChanged();
}

public void refresh(){
    Log.d("c",allItems.size()+"");
    allItems.clear();
    fillAllItems();
    Log.d("c",allItems.size()+"");
    adapter.notifyDataSetChanged();
}
}

我从MainActivity调用了刷新方法。

@Override
    public void onInserted() {
        fragment.refresh();
    }

我的Adapter就在这里。

public class EventsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context context;
private List<Item> allItems = new ArrayList();
private HideOrShowListener hideOrShowListener;
public static final int EVENT_TYPE = 1;
public static final int CATEGORY_TYPE = 0;
private int lastPosition;
private boolean flag = false;


public EventsAdapter(Context context,List<Item> allItems){
    this.context = context;
    hideOrShowListener =(HideOrShowListener) context;
    this.allItems = allItems;
}



@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view;
    switch (viewType){
        case CATEGORY_TYPE:
            view = LayoutInflater.from(context).inflate(R.layout.category_item,parent,false);
            return new CategoryViewHolder(view);
        case EVENT_TYPE:
            view = LayoutInflater.from(context).inflate(R.layout.events_item,parent,false);
            return new EventViewHolder(view);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    final Item item = allItems.get(position);
    switch (item.getType()){
        case CATEGORY_TYPE:
            ((CategoryViewHolder)holder).tvCategoryTitle.setText(item.getTitle());
            ((GradientDrawable)(((CategoryViewHolder)holder).categoryColorIcon).getBackground()).setColor(Color.parseColor(item.getColor()));

            ((CategoryViewHolder)holder).imgAddEvent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    hideOrShowListener.setHideOrShow(item,false);
                }
            });
            break;



        case EVENT_TYPE:
            String[] time = item.getTime().trim().split(":");
            int hour = Integer.parseInt(time[0]);

            ((EventViewHolder)holder).tvEventName.setText(item.getTitle());
            ((EventViewHolder)holder).tvTime.setText(hour<12?hour+" : "+time[1] +" am" : hour-12+" : "+time[1] +" pm" );
            ((EventViewHolder)holder).tvPlace.setText(item.getPlace());
            if(item.getDescription().length()==0) {
                item.setDescription("No Detail");
            }
            ((EventViewHolder)holder).tvDescription.setText(item.getDescription());

            if(item.isShow()){

                ((EventViewHolder)holder).descriptionLayout.animate().alpha(1).setDuration(200).setInterpolator(new AccelerateInterpolator()).start();
                ((EventViewHolder)holder).descriptionLayout.setVisibility(View.VISIBLE);
                ((EventViewHolder)holder).descriptionLayout.setSelected(true);

                ((EventViewHolder)holder).tvEdit.setVisibility(View.VISIBLE);
                ((EventViewHolder)holder).eventContainer.setSelected(true);

            }else{
                ((EventViewHolder)holder).descriptionLayout.setVisibility(View.GONE);
                ((EventViewHolder)holder).descriptionLayout.animate().alpha(0).setDuration(500).start();
                ((EventViewHolder)holder).descriptionLayout.setSelected(false);
                ((EventViewHolder)holder).eventContainer.setSelected(false);
                ((EventViewHolder)holder).tvEdit.setVisibility(View.INVISIBLE);
            }

            ((EventViewHolder)holder).tvEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    hideOrShowListener.setHideOrShow(item,true);
                }
            });
            break;
    }
}

@Override
public int getItemCount() {
    Log.d("c",allItems.size()+"");
    return allItems.size();
}

@Override
public int getItemViewType(int position) {
    if(allItems!=null){
        return allItems.get(position).getType();
    }
    return 0;
}

public class CategoryViewHolder extends RecyclerView.ViewHolder{
    private TextView tvCategoryTitle;
    private View categoryColorIcon;
    private ImageView imgAddEvent;
    public CategoryViewHolder(View itemView) {
        super(itemView);
        tvCategoryTitle = (TextView) itemView.findViewById(R.id.tvCategoryTitle);
        categoryColorIcon = itemView.findViewById(R.id.categoryColorIcon);
        imgAddEvent = (ImageView) itemView.findViewById(R.id.addEvent);
    }
}

public  class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    private LinearLayout descriptionLayout;
    private RelativeLayout eventContainer;
    private TextView tvEventName,tvTime,tvPlace,tvDescription,tvEdit;
    public EventViewHolder(View itemView) {
        super(itemView);
        descriptionLayout = (LinearLayout) itemView.findViewById(R.id.descriptionLayout);
        eventContainer = (RelativeLayout) itemView.findViewById(R.id.eventContainer);
        tvEventName = (TextView) itemView.findViewById(R.id.tvEventName);
        tvTime = (TextView) itemView.findViewById(R.id.tvTime);
        tvPlace = (TextView) itemView.findViewById(R.id.tvPlace);
        tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
        tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
        eventContainer.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(flag){
            allItems.get(lastPosition).setShow(false);
        }
        allItems.get(getAdapterPosition()).setShow(true);
        flag = true;
        lastPosition = getAdapterPosition();
        notifyDataSetChanged();
    }
}

public interface HideOrShowListener{
    public void setHideOrShow(Item item , boolean isEdit);
}

}

但是当我点击主页button并重新输入我的应用程序时,我的RecyclerView刷新了。这意味着notifyDatasetChanged方法中的onResume有效。但在我的刷新方法中,它并不起作用。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您确定要调用此方法:

@Override
public void onInserted() {
    fragment.refresh();
}

确保您拥有正确的片段实例。或者您可以简单地使用refresh()方法进行用户界面,并在片段中实现它。