我想知道这是否是好的做法,以及何时使用弱引用是一个好主意/坏主意......
创建适配器时,我向它传递一个对 fragment 的弱引用(以便它可以使用名为“EmailOrdersButton”的接口(interface)回调 fragment ):
WeakReference<OrderHistoryListFragment> weakFragment = new WeakReference<OrderHistoryListFragment>(OrderHistoryListFragment.this);
adapter = new OrderHistoryListAdapter(getActivity(), R.layout.order_history_list_item, -1, orderHistory, isInEditMode, weakFragment);
然后在我的适配器构造函数中我有这个:
public OrderHistoryListAdapter(Context mContext, int resource, int textViewResourceId, List<MOHistory> lastTransactionList, boolean isEditModeEnable, WeakReference weakFragment) {
mInflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.resource = resource;
this.context = mContext;
this.lastTransactionList = lastTransactionList;
originalList = this.lastTransactionList;
this.isEditModeEnable = isEditModeEnable;
try {
this.emailButtonCallback = ((EmailOrdersButton) weakFragment.get());
} catch (ClassCastException e) {
throw new ClassCastException("Fragment must implement EmailOrdersButton.");
}
}
将 fragment 的弱引用传递给适配器是一个好的做法吗?我想确保我的应用程序具有尽可能高的内存效率
最佳答案
使用弱引用,以便 fragment 松散耦合。如果不使用弱引用,它就不会被垃圾回收,因为 fragment 维护着对它的引用。
只要 fragment 的生命周期在 Activity 的生命周期内,就不需要使用 WeakReference。如果 fragment 的生存时间比 Activity 长,那么您应该使用 WeakReference 来避免系统销毁 Activity 时将 Activity 保留在对象图中。
关于java - 将弱 fragment 引用传递给列表适配器,这是一个好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35479179/