【发布时间】:2014-10-01 22:12:24
【问题描述】:
我有一些使用以下代码动态添加的片段:
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);
}
在我的一个片段中,我有一个计时器,我刚刚发现当片段被替换时,旧片段中的计时器仍在运行。我应该在片段生命周期的哪个位置终止计时器?
编辑:
好的,所以我在片段的 onStop() 方法中添加了 timer.cancel(),但是当我从操作栏上的按钮加载首选项时,也会调用 onStop()。这不是预期的效果。还有其他想法吗?
【问题讨论】:
-
签出 - androidlearnersite.wordpress.com/2017/02/27/… ..它解释了片段交易期间的片段生命周期与最新的 appcompat 版本
标签: java android android-fragments fragment