晚上好。我的应用程序从启动屏幕活动开始,为此活动我使用android:noHistory="true"
(对于MainActivity我也使用noHistory)。我的MainActivity是android.support.design.widget.NavigationView. Inside onCreate()
方法,我使用showMethod()
来绘制Home片段(主页)。
因此,当我单击“后退”按钮时,它绝对可以正常工作,应用程序会记住以正确顺序打开的所有片段。 但是!当我单击主页上的后退按钮(在应用程序启动后打开)时,显示空白的屏幕并显示先前的活动标题。
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
showHome();
}
Fragment fragment = null;
private void showHome(){
fragment = new Home();
if (fragment != null){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_main , fragment,fragment.getTag());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
@Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}
}
private void displaySelectedScreen(int id){
switch (id){
case R.id.nav_cafe_restaurants:
fragment = new Cafe_restaurants();
break;
case R.id.nav_cinemas:
fragment = new Cinemas();
break;
case R.id.nav_enjoys:
fragment = new Enjoys();
break;
case R.id.nav_night_clubs:
fragment = new Night_clubs();
break;
case R.id.nav_theaters:
fragment = new Theaters();
break;
case R.id.nav_museums:
fragment = new Museums();
break;
case R.id.nav_sports:
fragment = new Sports();
break;
case R.id.nav_sights:
fragment = new Sights();
break;
case R.id.nav_current_actions:
fragment = new Current_events();
break;
case R.id.nav_future_actions:
fragment = new Future_events();
break;
case R.id.nav_contacts:
fragment = new Contacts();
break;
}
if (fragment != null){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_main , fragment,fragment.getTag());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
您可以查看2个屏幕截图以了解我的问题。尝试自己解决几个小时。
答案 0 :(得分:1)
您的问题是,您要将初始Home
Fragment
添加到后堆栈中。这意味着从“无片段”到“本地”的事务可以撤消。当您按下后退按钮时,您将从堆栈中弹出该事务,这将使您不显示任何Fragment
。
只需从您的fragmentTransaction.addToBackStack(null);
方法中删除showHome()
。