调用replace()时片段的生命周期是什么? [英] What is the lifecycle of a fragment when replace() is called?

查看:99
本文介绍了调用replace()时片段的生命周期是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a number of fragments which are dynamically added using the following code:

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);
}

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

In one of my fragments I have a timer and I've just discovered that when the fragment is replaced the timer in the old fragment is still running. Where in my fragment's lifecycle should I kill the timer?

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

Okay so I added a timer.cancel() in the fragment's onStop() method but onStop() also gets called when I load the preferences from a button on the action bar. This is not the desired effect. Any other ideas?

推荐答案

我会杀死onStop()

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

引用API文档:

已停止
该片段不可见.主机活动已停止,或者片段已从活动中删除但已添加 到后面的堆栈.停止的片段仍然存在(所有状态和 会员信息由系统保留).但是,不是 不再对用户可见,如果活动为 被杀死.

Stopped
The fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack. A stopped fragment is still alive (all state and member information is retained by the system). However, it is no longer visible to the user and will be killed if the activity is killed.

片段生命周期:

这篇关于调用replace()时片段的生命周期是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆