gpt4 book ai didi

android-fragments - 安卓 : When to register and unregister for notifications?

转载 作者:行者123 更新时间:2023-12-04 07:45:37 24 4
gpt4 key购买 nike

我使用 Notifications每当数据更改时更新片段的接口(interface)。

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
}

}

关于 Android Lifecycle ,注册和注销通知的最佳点是什么?

Android Lifecycle

以下是一些场景:

场景一:
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();
}

请解释 为什么你会建议使用一个或另一个实现..或另一个!

最佳答案

这个问题没有一个普遍的答案。 onResume/onPause 可能会在大多数情况下给出预期的行为,但您可能会遇到想要更早或更晚执行此操作的情况。

不过,在不同的方面,关于风格和功能的两点 - 调用 super.onResume作为方法中的第一件事(和 super.onStop 作为最后一个)。这样,您的循环完全嵌套在“ super ”循环中,并且您避免了奇怪的错误和边缘情况。此外,总是调用notifyDataSetChanged 不是一个好主意。在 onResume .事实上,这可能是一个相当浪费的想法。

关于android-fragments - 安卓 : When to register and unregister for notifications?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15783041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com