我在活动启动时在NavigationView中选择默认片段, 它工作正常,但问题是当我按下后退按钮时,我看到一个空白视图。
我的活动
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private final String TAG = "MainActivity";
NavigationView navigationView;
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
String about_blog = "http://example.com/page/json/urls/p-about";
String contri = "http://example.com/page/json/urls/contribute";
String privy = "http://example.com/page/json/urls/privacy-rules";
String contact = "http://example.com/page/json/urls/contact_us";
String advert = "http://example.com/page/json/urls/advertise-here";
String spons = "http://example.com/page/json/urls/sponsor-us";
Fragment fragment = null;
if (id == R.id.menu_home) {
fragment = new PostFragment();
}
if (id == R.id.about_blog) {
fragment = new PageFragment();
} else if (id == R.id.nav_contri) {
fragment = new PageFragment();
} else if (id == R.id.nav_contact) {
fragment = new PageFragment();
} else if (id == R.id.nav_privy) {
fragment = new PageFragment();
} else if (id == R.id.nav_advert) {
fragment = new PageFragment();
} else if (id == R.id.spons) {
fragment = new PageFragment();
} else if (id == R.id.app_about) {
//fragment = new abtFragment();
} else if (id == R.id.settings) {
//fragment = new SettingFragment;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
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.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.menu_home);
navigationView.getMenu().performIdentifierAction(R.id.menu_home, 0);
}
详细说明,当我启动应用时,默认情况下会启动 PostFragment 。当我单击后退键而不是应用程序关闭时,我遇到一个空白页面。
拜托,我在这里做错了什么,如何纠正呢?
答案 0 :(得分:0)
我找到了解决方案here。只需粘贴此
即可 FragmentManager fm = getSupportFragmentManager();
fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override public void onBackStackChanged() { if (getSupportFragmentManager().getBackStackEntryCount() == 0) finish(); } });
在托管活动中onCreate
。
如果当前片段是后栈中的最后一个片段,那么它的作用是完成活动。