片段addToBackStack关闭应用程序 [英] Fragment addToBackStack closing App
问题描述
我没有找到我的问题的任何解决方案。
I didnt find any solution for my problem.
我有几个片段(动态创建的),但我的后退按钮不工作, pressing它将关闭应用程序,无论片段是积极的。
I got several Fragments (dynamically created), but my Back Button is not working at all, pressing it will close the App, whatever fragment is "active".
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.itemAdd:
FragmentTransaction tx = getFragmentManager().beginTransaction();
Fragment fragment = new NeuesProduktFrag();
tx.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right,
R.anim.slide_in_left, R.anim.slide_out_right);
tx.replace(R.id.main, fragment);
tx.addToBackStack(null);
tx.commit();
return true;
一切工作正常,但进入后NeuesProduktFrag片段和pressing后退按钮我的应用程序关闭。在不同的按钮等试了一下 重写onBack pressed是没有必要吧? addToBackStack应该做的伎俩不?
Everything works fine, but after entering "NeuesProduktFrag" Fragment and pressing Back-Button my App closes. Tried it in different Buttons etc. Overriding onBackPressed is not needed right ? addToBackStack should do the trick or not ?
推荐答案
在我struggeled很长一段时间,这是我最后的code:
After i struggeled a long time, this is my final Code:
@Override
public void onBackPressed() {
// initialize variables
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
// check to see if stack is empty
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
ft.commit();
}
else {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
Toast.makeText(this, "Nochmal drücken zum Beenden!", 4000).show();
this.lastBackPressTime = System.currentTimeMillis();
} else{
super.onBackPressed();
}
}
}
我用它在我的FragmentActivity并增加了双卡,关闭应用程序最后。
I used it in my FragmentActivity and added a double tab to close the App finally.
这篇关于片段addToBackStack关闭应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!