Android fragments Android:何时注册和注销通知?
我使用Android fragments Android:何时注册和注销通知?,android-fragments,android-lifecycle,android-adapter,Android Fragments,Android Lifecycle,Android Adapter,我使用通知接口在数据更改时更新片段 public interface Notifications { void register(ID id, Listener listener); void unregister(ID id, Listener listener); <T> void post(ID id, T value); interface Listener<T> { void onEvent(ID id, T
通知
接口在数据更改时更新片段
public interface Notifications {
void register(ID id, Listener listener);
void unregister(ID id, Listener listener);
<T> void post(ID id, T value);
interface Listener<T> {
void onEvent(ID id, T value);
}
enum ID {
CustomersUpdated,
ProductsUpdated
}
}
情景2:
请解释为什么建议使用一种或另一种实现。。或者别的 我会坚持场景2。尽管片段的
onPause()
和onResume()
顺序是线性的,但活动的顺序却不同
由于片段的暂停和恢复是在活动启动时调用的,因此在活动启动时将接收广播。但是,活动在失去可见性之前不会调用
onStop()
。在这种情况下,片段仍将处理广播,而其中包含的活动处于非活动状态,这听起来不是一个很好的主意 这个问题没有一个通用的答案。onResume/onPause在大多数情况下可能会给出预期的行为,但您可能会遇到希望更早或更晚执行此操作的情况
不过,另一方面,在风格和功能上有两点——调用
super.onResume
作为方法中的第一件事(调用super.onStop
作为最后一件事)。这样,您的周期完全嵌套在“超级”周期中,您可以避免奇怪的bug和边缘情况。此外,总是在onResume
中调用notifyDataSetChanged
不是一个好主意。事实上,这可能是一个相当浪费的想法。为什么不在应用程序类中注册和取消注册?
public class ProductsListFragment extends BaseFragment
implements Notifications.Listener {
@Override
public void onStart() {
mAdapter.notifyDataChanged();
register(Notifications.ID.ProductsUpdated, this)
super.onStart();
}
@Override
public void onStop() {
unregister(Notifications.ID.ProductsUpdated, this)
super.onStop();
}
@Override
public void onEvent(Notifications.ID id, Object value) {
mAdapter.notifyDataChanged();
}
public class ProductsListFragment extends BaseFragment
implements Notifications.Listener {
@Override
public void onResume() {
mAdapter.notifyDataChanged();
register(Notifications.ID.ProductsUpdated, this)
super.onResume();
}
@Override
public void onPause() {
unregister(Notifications.ID.ProductsUpdated, this)
super.onPause();
}
@Override
public void onEvent(Notifications.ID id, Object value) {
mAdapter.notifyDataChanged();
}