我的应用程序具有这样的结构
MainActivity扩展 ActionBarActivity -- 按下按钮时 --> ListFragment --按下列表项-->片段
在 Fragment中并且如果按下返回键,它会直接转到MainActivity 。我如何让它去 ListFragment
以下是我期望它做的事情
片段*----按下后退键--> *ListFragment --按下后退键 ---> MainActivity扩展 ActionBarActivity
以下代码是我在 mainactivity 和 listfragment 中用来启动任何片段的代码
.........................................
case 5:
fragment = new HomeFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
//getSupportActionBar().setSubtitle(navMenuTitles[position]);
//setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
更新
现在我已将以下代码添加到我的 MainActivity
@Override
public void onBackPressed() {
Fragment frag = getSupportFragmentManager().findFragmentById(R.id.frame_container);
if((frag instanceof CommonMasjidPrayerTimes)) {
finish();
}
}
And following code to my listfragment
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
// fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
if (masjidNamazTimings != null) {
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.frame_container, masjidNamazTimings).commit();
}
Now when I press the backbutton on my list fragment or fragment it doesnt go back