从RecyclerView适配器更新“活动"或“片段"的视图
我正在尝试更新活动中位于TextView中的文本,以显示从RecyclerView中删除项目时的总价.但是,如何从适配器更新属于活动的视图?
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?
这是解决方案.
-
创建一个名为
ItemsInteractionListener
的公共接口,该接口具有一个方法void onTotalPriceChanged(double newPrice);
适配器内
Create a public interface called
ItemsInteractionListener
which has a methodvoid onTotalPriceChanged(double newPrice);
inside adapter
在适配器内部创建名为 mListener
的接口的对象
Create an object of the interface called mListener
inside the adapter
为 mListener
创建一个名为 double getTotalPrice()
的私有方法,该方法从列表中计算总价格.
Create a private method called double getTotalPrice()
which calculates total price from the list.
在活动中实施 ItemsInteractionListener
.在 void onTotalPriceChanged(double newPrice);
内,将新价格设置为TextView.
Implement ItemsInteractionListener
in activity.
Inside void onTotalPriceChanged(double newPrice);
, set the new price to the TextView.
创建适配器后,通过调用在步骤3之前创建的设置器,将侦听器设置为 this
.
After creating adapter, set the listener to this
by calling the setter you created before in step 3.
在适配器内部调用 mListener.onTotalPriceChanged(newPrice);
.即添加或删除项目时.
Call mListener.onTotalPriceChanged(newPrice);
inside adapter whenever a change is made. ie, when adding or deleting items.