调用replace()时片段的生命周期是多少?

Leo*_*eon 17 java android fragment android-fragments

我有许多片段,使用以下代码动态添加:

private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }
}

private void selectItem(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    if(position == 0){
        fragment = new FirstFragment();
    }
    else if(position == 1){
        fragment = new SecondFragment();
    }
    else if(position == 2){
        fragment = new ThirdFragment();
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

    // update selected item and title, then close the drawer
    mDrawerList.setItemChecked(position, true);
    setTitle(mCalculatorTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
}
Run Code Online (Sandbox Code Playgroud)

在我的一个片段中,我有一个计时器,我刚刚发现当更换片段时,旧片段中的计时器仍在运行.在片段的生命周期中,我应该杀死计时器吗?

编辑:

好的,所以我在片段的onStop()方法中添加了timer.cancel(),但是当我从操作栏上的按钮加载首选项时,也会调用onStop().这不是理想的效果.还有其他想法吗?

pjc*_*jco 10

我会杀死任何计时器或异步工作 onStop()

http://developer.android.com/guide/components/fragments.html#Lifecycle

引用API文档:

停止
片段不可见.主机活动已停止或片段已从活动中删除但已添加到后台堆栈.已停止的片段仍处于活动状态(系统会保留所有状态和成员信息).但是,它不再对用户可见,并且如果活动被杀死将被杀死.

片段生命周期:

片段生命周期

  • 好吧,这似乎与正在发生的事情有关,但是当在相同的活动中替换片段时,是否有任何被调用的东西? (2认同)