android - 如何在 ViewGroup 派生类中管理生命周期?

标签 android

我在一个显示一些外部数据的运行图的 Activity 中有一堆代码。由于 Activity 代码变得有点杂乱,我决定提取这段代码并创建一个 GraphView 类:

public class GraphView extends LinearLayout {
    public GraphView(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater inflater = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        inflater.inflate(R.layout.graph_view, this, true);
    }

    public void start() {
        // Perform initialization (bindings, timers, etc) here
    }

    public void stop() {
        // Unbind, destroy timers, yadda yadda
    }
        .
        .
        .
}

将内容移入这个新的 LinearLayout 派生类很简单。但是有一些生命周期管理代码与创建和销毁此图使用的计时器和事件监听器相关联(例如,如果 Activity 暂停,我不希望这个东西在后台轮询)。

来自 MS Windows 背景,我有点希望找到可覆盖的 onCreate()onDestroy() 方法或类似的方法,但我没有找到任何东西LinearLayout (或其任何继承的成员)中的排序。必须将所有这些初始化代码留在 Activity 中,然后必须将其传递到 View 中,这似乎违背了将所有这些代码封装到可重用 View 中的最初目的。

我最终在 View 中添加了两个额外的公共(public)方法:start()stop()。我分别从 Activity 的 onResume()onPause() 方法进行这些调用。

这似乎可行,但感觉就像我在这里使用胶带一样。有谁知道这通常是如何完成的?我觉得我错过了什么......

最佳答案

您可能能够从覆盖 protected void onAttachedToWindow()protected void onDetachedFromWindow() 中获得一些用处,我从未尝试过,但它们可能被称为近似当你想要的时候。

关于android - 如何在 ViewGroup 派生类中管理生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2358745/

相关文章:

android - 将数据发布到 MVC Web Api 时 Volley 库无法工作

java - Android 附件通过 HTTPS 上传

iphone - 手机开发: interact with the call?

java - 使用 TextWatcher addTextChangedListener() 在 EditText 中设置文本时出现 IndexOutOfBoundsException

android 客户端中的 java.io.StreamCorrupted Exception`

java - 启动独立 SDK 管理器不起作用

android - 谷歌距离矩阵网络服务限制

java - Qt 和 Android Gallery - 使用 QAndroidJniObject 的 MediaStore

android - 安卓上的服务?

android - 如何在android服务类中获取上下文