Updating views of Activity or Fragment from a RecyclerView adapter

旧巷老猫 提交于 2021-02-08 10:30:56

问题


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?

screenshot


回答1:


Here is the solution.

  1. Create a public interface called ItemsInteractionListener which has a method void onTotalPriceChanged(double newPrice); inside adapter

  2. Create an object of the interface called mListener inside the adapter

  3. Create a public setter for mListener

  4. Create a private method called double getTotalPrice() which calculates total price from the list.

  5. Implement ItemsInteractionListener in activity. Inside void onTotalPriceChanged(double newPrice);, set the new price to the TextView.

  6. After creating adapter, set the listener to this by calling the setter you created before in step 3.

  7. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!