简体   繁体   中英

Remove RecyclerView adapter item from Activity

I have Quote List class QuoteListFragment. where I am loading data in adapter from server like this

private ArrayList<Quote> quotes;
quotes = response.body();
NewQuoteAdapter adapter = new NewQuoteAdapter(getContext(), response.body());
mQuoteList.setAdapter(adapter);

and RecyclerView Adapter called NewQuoteAdapter

I am displaying Item in details with QuoteViewFragment . I have implemented a button called "delete" in this fragment and I want to give the user a chance to delete that quote from fragment so When the user goes back to the list, it disappears from the list. I have no idea how to achieve this. Let me know if someone can give me a solution for this. Thanks

well you have a list, and adapter, and a recyclerview

ArrayList<String> myQuoteList = new ArrayList<String>();
MyCustomAdapter adapter = new MyCustomAdapter(myQuoteList);
rcvQuotes.setAdapter(adapter);

Then in your delete you can just do

private void deleteAtIndex(int index){
      myQuoteList.remove(index);
      adapter.notifyDataSetChanged();
}

//make a interface.

public interface fragmentCallback{
     boolean onQuoteDeleted(Quote deleteQuote);
}

have your activity implement the interface:

myActivity implements fragmentCallback{
     public boolean onQuoteDeleted(Quote deletedQuote){
         if(myQuotelist.contains(deleteQuote){
              myQuoteList.remove(deleteQuote);
              adapter.notifyDataSetChanged();
         }
     }
}

then in fragment simpley

myFragment.setQuote(selectedQuote);

inside of fragment just do:

       @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try{
            mFragmentCallback = (IFragmentCallback) context;

        }catch (Exception ex){
            A35Log.e(TAG, "Parent Context does not implement fragmentCallback");

        }
    }

public void setQuote(Quote showQuote){
     mSelectedQuote = showQuote;
}

btnDelete_onClick(){
    if(mFragmentCallback != null){
         mFragmentCallback.onDeleteQuote(mSelectedQuote);
    }
}

you can handle it by selected index of the row, or by last index, or first index, or you can add a long touch listener or trash can to the row item. how you get the index is up to you.

That's it, that is all there is to it.

Arraylist.remove(index)

recycleradapter.notifydatasetchanged()

Get the index of clicked item eg index = 4 list of quote eg quotesList.

quotesList.remove(index);
adapter.notifyDataSetChanged();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM