问题
I am trying to update the text in a TextView which is located in the activity to show the total price when an item is deleted from RecyclerView. But how can I update a view which belongs to activity from an adapter?
回答1:
Here is the solution.
Create a public interface called
ItemsInteractionListener
which has a methodvoid onTotalPriceChanged(double newPrice);
inside adapterCreate an object of the interface called
mListener
inside the adapterCreate a public setter for
mListener
Create a private method called
double getTotalPrice()
which calculates total price from the list.Implement
ItemsInteractionListener
in activity. Insidevoid onTotalPriceChanged(double newPrice);
, set the new price to the TextView.After creating adapter, set the listener to
this
by calling the setter you created before in step 3.Call
mListener.onTotalPriceChanged(newPrice);
inside adapter whenever a change is made. ie, when adding or deleting items.
来源:https://stackoverflow.com/questions/47957822/updating-views-of-activity-or-fragment-from-a-recyclerview-adapter