add Theme Listener
添加主题变化监听器
注册一个监听器以接收主题切换事件通知。当调用 changeInnerTheme 或 changeCustomTheme 方法且主题实际发生变化时,所有已注册的监听器都会收到 onThemeChanged 回调。
使用场景:
- 需要在主题切换时更新自定义 UI 组件
- 需要在主题变化时重新加载资源或刷新界面
- 需要同步主题状态到其他模块
Context 参数的优势:
- 监听器无需自己持有 Context 引用,避免潜在的内存泄漏
- 可以直接使用传入的 Context 进行 UI 操作(如 Activity.recreate())
- 通过 Context 获取资源或调用其他需要 Context 的方法
使用示例:
public class MyActivity extends AppCompatActivity {
private OnThemeListener themeListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 创建监听器
themeListener = new OnThemeListener() {
@Override
public void onThemeChanged(Context context, String oldTheme, String newTheme) {
// 使用传入的 context 重新创建 Activity
if (context instanceof Activity) {
((Activity) context).recreate();
}
}
};
// 添加监听器
IMKitThemeManager.addThemeListener(themeListener);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 移除监听器,避免内存泄漏
IMKitThemeManager.removeThemeListener(themeListener);
}
}
Content copied to clipboard
注意事项:
- 同一个监听器对象不会被重复添加
- 请在合适的时机(如 Activity/Fragment 的 onDestroy)移除监听器,避免内存泄漏
- 监听器回调在主题切换所在的线程执行,通常是主线程
Parameters
listener
主题变化监听器,不能为 null