我在android studio中使用navbar。我正在尝试通过getSupportFragmentManager()。beginTransaction()。replace()来替换片段,但它不起作用并且不断给我错误。这是代码:
public class UserNavbar extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private DrawerLayout mydrawerlayout;
private ActionBarDrawerToggle atoggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_navbar);
mydrawerlayout = (DrawerLayout)findViewById(R.id.drawer_layout);
atoggle = new ActionBarDrawerToggle(this,mydrawerlayout,R.string.open,R.string.close); //Done
mydrawerlayout.addDrawerListener(atoggle);
atoggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.home:
getSupportFragmentManager().beginTransaction().replace(R.id.frame, new User_Home_Fragment()).commit();
break;
case R.id.personalinformation:
getSupportFragmentManager().beginTransaction().replace(R.id.frame, new Personal_Info_Frag()).commit();
break;
case R.id.settings:
getSupportFragmentManager().beginTransaction().replace(R.id.frame, new Settings_Frag()).commit();
break;
}
mydrawerlayout.closeDrawer(GravityCompat.START);
return true;
}}
开发了User_Home_Fragment(),Personal_Info_Frag()和Settings_Frag()。如果需要,我也会发布它们。
如果有人有任何建议,我会很感激。问候
我想你错过了新的关键字因为becase replace方法有两个参数,第一个是容器id,第二个是片段实例。
getSupportFragmentManager().beginTransaction().replace(R.id.frame, new User_Home_Fragment()).commit();
请在致电你的片段之前写下新的关键字。胃内
new User_Home_Fragment()